知識點
1. sched模塊,准確的說,它是一個調度(延時處理機制),每次想要定時執行某任務都必須寫入一個調度。
(1)生成調度器:
s = sched.scheduler(time.time,time.sleep)
第一個參數是一個可以返回時間戳的函數,第二個參數可以在定時未到達之前阻塞。可以說sched模塊設計者是“在下很大的一盤棋”,比如第一個函數可以是自定義的一個函數,不一定是時間戳,第二個也可以是阻塞socket等。
(2)加入調度事件
其實有enter、enterabs等等,我們以enter為例子。
s.enter(x1,x2,x3,x4)
四個參數分別為:間隔事件、優先級(用於同時間到達的兩個事件同時執行時定序)、被調用觸發的函數,給他的參數(注意:一定要以tuple給如,如果只有一個參數就(xx,))
(3)運行
s.run()
注意sched模塊不是循環的,一次調度被執行后就Over了,如果想再執行,請再次enter
2. time模塊,它是python自帶的模塊,主要用於時間的格式轉換和處理。
time.sleep(s)
推遲調用線程的運行,s指秒數
3. os模塊也是python自帶的模塊,os模塊中的system()函數可以方便地運行其他程序或者腳本。
os.system(cmd)
cmd 為要執行的命令,近似於Windows下cmd窗口中輸入的命令。
下面我們來看具體實例:
1.定時任務代碼
#定時執行任務命令 import time,os,sched schedule = sched.scheduler(time.time,time.sleep) def perform_command(cmd,inc): os.system(cmd) print('task') def timming_exe(cmd,inc=60): schedule.enter(inc,0,perform_command,(cmd,inc)) schedule.run() print('show time after 2 seconds:') timming_exe('echo %time%',2)
2.周期性執行任務
import time,os,sched schedule = sched.scheduler(time.time,time.sleep) def perform_command(cmd,inc): #在inc秒后再次運行自己,即周期運行 schedule.enter(inc, 0, perform_command, (cmd, inc)) os.system(cmd) def timming_exe(cmd,inc=60): schedule.enter(inc,0,perform_command,(cmd,inc)) schedule.run()#持續運行,直到計划時間隊列變成空為止 print('show time after 2 seconds:') timming_exe('echo %time%',2)
3.循環執行命令
import time,os def re_exe(cmd,inc = 60): while True: os.system(cmd) time.sleep(inc) re_exe("echo %time%",5)