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