admin管理员组

文章数量:1794759

python中的schedule模块定时执行任务

python中的schedule模块定时执行任务

schedule模块支持python2.7、3.5、3.6,是一个轻量级的定时任务调度的库,可以实现每分钟、每小时、每天(可具体到哪个时间点)、周几等,在特定的时间定时执行任务。

linux环境下安装(windows下没有测试):

sudo pip install schedule

使用方法:

import schedule import time def job1(): print("I'm working...") def job2(): print("I'm working... in job2") def job3(name): print "My name is:"+name # 每10分钟执行一次job1函数 schedule.every(10).minutes.do(job1) # 每10秒执行一次job函数 schedule.every(10).seconds.do(job1) # 当every()没参数时默认是1小时/分钟/秒执行一次job1函数 schedule.every().hour.do(job1) # 具体到每天的具体时间点执行任务 schedule.every().day.at("12:00").do(job1) schedule.every().monday.do(job1) # 每隔5到10天执行一次任务 schedule.every(5).to(10).days.do(job1) # 每周一的这个时候执行任务 schedule.every().monday.do(job1) # 每周三12点执行任务 schedule.every().wednesday.at("12:00").do(job) # 可以同时定时执行多个任务,但是每个任务是按顺序执行 schedule.every(10).seconds.do(job2) # 如果job函数有有参数时,如job3函数 schedule.every(10).seconds.do(job3,"xiaoming") while True: # 启动服务(运行所有可以运行的任务) schedule.run_pending() time.sleep(1)

注:do中内容带括号代表方法的返回值,不带括号代表方法本身。

while True的作用:schedule其实就只是一个定时器,在这个死循环中,schedule.run_pending()能保持schedule一直运行,去查询上面那些任务。

局限性:

1、需要定时运行的函数job不应当是死循环类型的,也就是说,这个线程应该有一个执行完毕的出口。一是因为线程万一僵死,会是非常棘手的问题;二是下一次定时任务还会开启一个新的线程,执行次数多了就会演变成灾难。

2、如果schedule的时间间隔设置得比job执行的时间短,一样会线程堆积形成灾难,也就是说,我job的执行时间是1个小时,但是我定时任务设置的是5分钟一次,那就会一直堆积线程。

本文标签: 模块Pythonschedule