Python 3实现定时任务有四种方式:
1、使用time模块
time模块提供了sleep函数,可以让程序暂停执行一段时间,从而达到定时任务的效果。使用方法如下:
import time
while True:
# 执行定时任务的代码
# 每隔1小时执行一次
time.sleep(3600)
2、使用datetime模块
datetime模块提供了datetime.datetime.now()函数,可以获取当前时间,从而实现定时任务。使用方法如下:
import datetime
while True:
# 获取当前时间
now = datetime.datetime.now()
# 如果是每天的9点,则执行定时任务的代码
if now.hour == 9:
# 执行定时任务的代码
# 每隔1小时执行一次
time.sleep(3600)
3、使用sched模块
sched模块提供了sched.scheduler类,可以实现定时任务。使用方法如下:
import sched
import time
# 初始化sched模块的scheduler类
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)
def perform_command(cmd, inc):
# 定时任务要做的事情
print('执行任务:', cmd)
# 安排inc秒后再次运行自己,即周期运行
schedule.enter(inc, 0, perform_command, (cmd, inc))
def main(cmd, inc = 60):
# enter用来安排某事件的发生时间,从起第n秒开始启动
schedule.enter(0, 0, perform_command, (cmd, inc))
# 持续运行,直到计划时间队列变成空为止
schedule.run()
if __name__ == '__main__':
main('定时任务')
4、使用APScheduler库
APScheduler是一个轻量级的Python定时任务框架,可以按照指定的时间间隔或者指定时间点执行任务,使用方法如下:
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=3)
def timed_job():
# 定时任务要做的事情
print('This job is run every three minutes.')
sched.start()