使用python進行job管理的schedule模塊,簡單好用,在這里記錄一下。
詳細源碼可以參考這里 https://github.com/dbader/schedule
安裝方法
pip install schedule
使用方法
import schedule import time def test(): print("I'm working...") def test2(): print("I'm working... in job2") # 每10分鍾執行一次job函數 schedule.every(10).minutes.do(test) # 每10秒執行一次job函數 schedule.every(10).seconds.do(test) # 當every()沒參數時默認是1小時/分鍾/秒執行一次job函數 schedule.every().hour.do(test) schedule.every().day.at("10:30").do(test) schedule.every().monday.do(test) # 具體某一天某個時刻執行一次job函數 schedule.every().wednesday.at("13:15").do(test) # 可以同時定時執行多個任務,但是每個任務是按順序執行 schedule.every(10).seconds.do(job2) # 如果job函數有有參數時,這么寫 schedule.every(10).seconds.do(job,"參數") while True: # 啟動服務 schedule.run_pending() time.sleep(1)
運行該程序之后,可以定時的進行執行。除了代碼中提到的方法之外,還有例如seconds等的一些方法,可以參考源碼。
TIPS
注意,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 #threading.Thread(target=loop,args=(i,loops[i])) 17 18 schedule.every(10).seconds.do(run_threaded,job) 19 schedule.every(10).seconds.do(run_threaded,job2) 20 21 22 while True: 23 schedule.run_pending() 24 time.sleep(1)
有如下輸出:
I’m working… in job1 start
I’m working… in job2
I’m working… in job1 start
I’m working… in job2
I’m working… in job1 end
可見在並行的執行。
如果想要對線程的數量有所控制,“If you want tighter control on the number of threads use a shared jobqueue and one or more worker threads”,則可以采用如下方法:
1 import Queue 2 import time 3 import threading 4 import schedule 5 6 7 def job(): 8 print("I'm working") 9 10 11 def worker_main(): 12 while 1: 13 job_func = jobqueue.get() 14 job_func() 15 16 jobqueue = Queue.Queue() 17 18 schedule.every(10).seconds.do(jobqueue.put, job) 19 schedule.every(10).seconds.do(jobqueue.put, job) 20 schedule.every(10).seconds.do(jobqueue.put, job) 21 schedule.every(10).seconds.do(jobqueue.put, job) 22 schedule.every(10).seconds.do(jobqueue.put, job) 23 24 worker_thread = threading.Thread(target=worker_main) 25 worker_thread.start() 26 27 while 1: 28 schedule.run_pending() 29 time.sleep(1)
