python中使用schedule模块定时执行任务
python中有一个轻量级的定时任务调度的库:schedule。他可以完成每分钟,每小时,每天,周几,特定日期的定时任务。因此十分方便我们执行一些轻量级的定时任务.
代码如下:
1 import schedule 2 import time 3 4 def job(name): 5 print("her name is : ", name) 6 7 name = "longsongpong" 8 schedule.every(10).minutes.do(job, name) 9 schedule.every().hour.do(job, name) 10 schedule.every().day.at("10:30").do(job, name) 11 schedule.every(5).to(10).days.do(job, name) 12 schedule.every().monday.do(job, name) 13 schedule.every().wednesday.at("13:15").do(job, name) 14 15 while True: 16 schedule.run_pending() 17 time.sleep(1)
- 每隔十分钟执行一次任务
- 每隔一小时执行一次任务
- 每天的10:30执行一次任务
- 每隔5到10天执行一次任务
- 每周一的这个时候执行一次任务
- 每周三13:15执行一次任务
- run_pending:运行所有可以运行的任务
schedule方法是串行的,也就是说,如果各个任务之间时间不冲突,那是没问题的;如果时间有冲突的话,会串行的执行命令
代码如下:
1 import schedule 2 import time 3 import threading 4 5 def job(): 6 print("I'm working... in job1 start") 7 time.sleep(15) 8 print("I'm working... in job1 end") 9 10 def job2(): 11 print("I'm working... in job2") 12 13 schedule.every(10).seconds.do(job) 14 schedule.every(10).seconds.do(job2) 15 16 while True: 17 schedule.run_pending() 18 time.sleep(1)
结果如下:
I’m working… in job1 start
I’m working… in job1 end
I’m working… in job2
如果要多线程并发运行
代码如下:
1 import schedule 2 import time 3 import threading 4 5 def job(): 6 print("I'm working... in job1 start") 7 time.sleep(15) 8 print("I'm working... in job1 end") 9 10 def job2(): 11 print("I'm working... in job2") 12 13 def run_threaded(job_func): 14 job_thread = threading.Thread(target=job_func) 15 job_thread.start() 16 17 schedule.every(10).seconds.do(run_threaded,job) 18 schedule.every(10).seconds.do(run_threaded,job2) 19 20 21 while True: 22 schedule.run_pending() 23 time.sleep(1)
结果如下:
1 I'm working... in job1 start 2 I'm working... in job2 3 I'm working... in job1 start 4 I'm working... in job2 5 I'm working... in job1 end 6 I'm working... in job1 start 7 I'm working... in job2