Python標準庫筆記(5) — sched模組
目錄[-]
事件排程
sched
模組內容很簡單,只定義了一個類。它用來最為一個通用的事件排程模組。
class sched.scheduler(timefunc, delayfunc)
這個類定義了排程事件的通用介面,它需要外部傳入兩個引數,timefunc
是一個沒有引數的返回時間型別數字的函式(常用使用的如time模組裡面的time),delayfunc
應該是一個需要一個引數來呼叫、與timefunc的輸出相容、並且作用為延遲多個時間單位的函式(常用的如time模組的sleep)。
下面是一個列子:
import sched, time s = sched.scheduler(time.time, time.sleep) # 生成排程器 def print_time(): print "From print_time", time.time() def print_some_times(): print time.time() s.enter(5, 1, print_time, ()) # 加入排程事件 # 四個引數分別是: # 間隔事件(具體值決定與delayfunc, 這裡為秒); # 優先順序(兩個事件在同一時間到達的情況); # 觸發的函式; # 函式引數; s.enter(10, 1, print_time, ()) # 執行 s.run() print time.time() if __name__ == '__main__': print_some_times()
看到的輸出結果,隔5秒中執行第一個事件,隔10秒後執行第二個事件:
1499259731.99
From print_time 1499259736.99
From print_time 1499259741.99
1499259741.99
在多執行緒場景中,會有執行緒安全問題,run()函式會阻塞主執行緒。官方建議使用threading.Timer
類代替:
import time from threading import Timer def print_time(): print "From print_time", time.time() def print_some_times(): print time.time() Timer(5, print_time, ()).start() Timer(10, print_time, ()).start() time.sleep(11) # 阻塞主執行緒,等待排程程式執行完畢,再執行後面內容 print time.time() if __name__ == '__main__': print_some_times()
Scheduler物件方法
scheduler物件擁有下面這些方法或屬性:
- scheduler.enterabs(time, priority, action, argument)
加入一個事件,time
引數應該是一個與傳遞給建構函式的timefunc
函式的返回值相相容的數值型別。在同一時間到達的事件將按照priority
順序執行。
執行事件其實就是執行action(argument)
。argument必須是一個包含action
引數的序列。
返回值是一個事件,它可以用於稍後取消事件(請參見cancel()
)。
- scheduler.enter(delay, priority, action, argument)
安排一個事件來延遲delay
個時間單位。除了時間外,其他引數、含義和返回值與enterabs()
的值相同。其實內部enterabs
就是用來被enter
呼叫。
- scheduler.cancel(event)
從佇列中刪除事件。如果事件不是當前佇列中的事件,則該方法將跑出一個ValueError
。
- scheduler.empty()
判斷佇列是否為空。
- scheduler.run()
執行所有預定的事件。這個函式將等待(使用傳遞給建構函式的delayfunc()
函式),然後執行事件,直到不再有預定的事件。
任何action
或delayfunc
都可以引發異常。在這兩種情況下,排程器將保持一個一致的狀態並傳播異常。如果一個異常是由action
引起的,就不會再繼續執行run()
。
- scheduler.queue
只讀屬性,返回一個即將到達的事件列表(按到達事件排序),每個事件都是有time
、priority
、action
、argument
組成的namedtuple
。