sched — 事件排程器

原始碼: Lib/sched.py


sched 模組定義了一個實現了通用事件排程器的類

class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep)

scheduler 類定義了一個通用的事件排程介面。它需要兩個函式來實際處理“外部世界”—— timefunc 應該可以無引數呼叫,並返回一個數字(“時間”,單位不限)。delayfunc 函式應該可以帶一個引數呼叫,該引數與 timefunc 的輸出相容,並且應該延遲這麼多時間單位。在每個事件執行後,delayfunc 也會以引數 0 呼叫,以允許其他執行緒在多執行緒應用程式中執行。

3.3 版本發生變更: timefuncdelayfunc 引數是可選的。

3.3 版本發生變更: scheduler 類可以在多執行緒環境中安全使用。

示例

>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     # despite having higher priority, 'keyword' runs after 'positional' as enter() is relative
...     s.enter(5, 1, print_time, kwargs={'a': 'keyword'})
...     s.enterabs(1_650_000_000, 10, print_time, argument=("first enterabs",))
...     s.enterabs(1_650_000_000, 5, print_time, argument=("second enterabs",))
...     s.run()
...     print(time.time())
...
>>> print_some_times()
1652342830.3640375
From print_time 1652342830.3642538 second enterabs
From print_time 1652342830.3643398 first enterabs
From print_time 1652342835.3694863 positional
From print_time 1652342835.3696074 keyword
From print_time 1652342840.369612 default
1652342840.3697174

排程器物件

scheduler 例項具有以下方法和屬性

scheduler.enterabs(time, priority, action, argument=(), kwargs={})

排程一個新事件。time 引數應該是一個數字型別,與傳遞給建構函式的 timefunc 函式的返回值相容。排程在同一 time 的事件將按其 priority 的順序執行。數字越小表示優先順序越高。

執行事件意味著執行 action(*argument, **kwargs)argument 是一個序列,包含 action 的位置引數。kwargs 是一個字典,包含 action 的關鍵字引數。

返回值是一個事件,可用於稍後取消事件(參見 cancel())。

3.3 版本發生變更: argument 引數是可選的。

3.3 版本發生變更: 添加了 kwargs 引數。

scheduler.enter(delay, priority, action, argument=(), kwargs={})

排程一個事件,使其在 delay 更多時間單位後執行。除了相對時間,其他引數、效果和返回值與 enterabs() 相同。

3.3 版本發生變更: argument 引數是可選的。

3.3 版本發生變更: 添加了 kwargs 引數。

scheduler.cancel(event)

從佇列中移除事件。如果 event 不在當前佇列中,此方法將引發 ValueError

scheduler.empty()

如果事件佇列為空,則返回 True

scheduler.run(blocking=True)

執行所有已排程的事件。此方法將等待(使用傳遞給建構函式的 delayfunc 函式)下一個事件,然後執行它,依此類推,直到沒有更多已排程的事件。

如果 blocking 為 false,則執行即將到期的已排程事件(如果有),然後返回排程器中下一個已排程呼叫的截止時間(如果有)。

actiondelayfunc 都可以引發異常。在這兩種情況下,排程器將保持一致狀態並傳播異常。如果 action 引發異常,則將來呼叫 run() 時將不再嘗試該事件。

如果一系列事件的執行時間比下一個事件到來之前可用時間長,排程器將簡單地滯後。不會丟棄任何事件;呼叫程式碼負責取消不再相關的事件。

3.3 版本發生變更: 添加了 blocking 引數。

scheduler.queue

只讀屬性,返回按執行順序排列的即將發生的事件列表。每個事件都顯示為一個 命名元組,包含以下欄位:time, priority, action, argument, kwargs。