標籤:safe hold argument 引入 env empty time can tps
python定時任務使用方法如下:
import schedshelder = sched.scheduler(time.time, time.sleep)shelder.enter(2, 0, print_time, ())shelder.run()
執行順序說明如下:
1、建立一個定時任務執行的執行個體2、將定時任務插入到執行隊列中3、啟動定時任務enter方法的參數說明:第一個參數是在任務啟動多少秒後執行第二個參數是任務優先順序第三個參數是要執行的方法第四個參數是方法要傳進去的參數,沒有的話直接使用()
執行個體1:順序執行
import timeimport scheddef print_time(): print ‘now the time is:‘,time.time()def do_some_times(): print ‘begin time:‘,time.time() shelder.enter(2, 0, print_time, ()) shelder.enter(2, 0, print_time, ()) shelder.enter(5, 1, print_time, ()) shelder.run() print ‘end time:‘,time.time()do_some_times()
運行結果:
begin time: 1525682354.85
now the time is: 1525682356.86
now the time is: 1525682356.86
now the time is: 1525682359.86
end time: 1525682359.86
這裡後面的時間都是一樣的是因為表示的是加入到隊列時間
在涉及到多線程的問題時使用上面的方法就會引入安全執行緒的限制,官方手冊上也做了充分的說明,具體如下:
In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.最終的意思就是使用threading的Timer進行替代
執行個體2:安全執行緒的
from threading import Timerimport timedef print_time(): print ‘now the time is:‘,time.time()def print_times(): print ‘begin time is:‘,time.time() Timer(5, print_time,(())).start() Timer(10, print_time,(())).start() time.sleep(2) print ‘end time is:‘,time.time() print_times()
運行結果:
begin time is: 1525682440.55
end time is: 1525682442.55
now the time is: 1525682445.55
now the time is: 1525682450.55
執行個體3:任務自調度
from threading import Timerimport timecounttimes=3def print_time(): global counttimes if counttimes > 0: print ‘now the time is %d,%f:‘ % (counttimes,time.time()) Timer(5, print_time,(())).start() counttimes -= 1def print_times(): print ‘begin time is:‘,time.time() Timer(5, print_time,(())).start() time.sleep(2) print ‘end time is:‘,time.time()print_times()
運行結果:
begin time is: 1525682594.3
end time is: 1525682596.3
now the time is 3,1525682599.300889:
now the time is 2,1525682604.302403:
now the time is 1,1525682609.302912:
附錄
常用schelder方法:
scheduler.enterabs(time, priority, action, argument)scheduler.enter(delay, priority, action, argument)scheduler.cancel(event)刪除一個任務事件scheduler.empty()任務隊列是否為空白scheduler.run()啟動任務,執行下一個任務時會進行等待scheduler.queue任務隊列
參考文檔:https://docs.python.org/2/library/sched.html
python 定時服務模組