首頁  >  文章  >  後端開發  >  Python標準庫之sched模組介紹

Python標準庫之sched模組介紹

零下一度
零下一度原創
2017-07-20 18:06:391880瀏覽

事件調度

  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.99From print_time 1499259736.99From print_time 1499259741.991499259741.99

  在多執行緒場景中,會有執行緒安全性問題,run()函數會阻塞主執行緒。官方建議使用threading.Timer類別來取代:

import timefrom threading import Timerdef 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()函數),然後執行事件,直到不再有預定的事件。

  任何actiondelayfunc都可以引發例外。在這兩種情況下,調度器將保持一個一致的狀態並傳播異常。如果一個異常是由action引起的,就不會再繼續執行run()

  • scheduler.queue

    #

  只讀屬性,傳回一個即將到達的事件清單(按到達事件排序),每個事件都是有timepriorityactionargument組成的namedtuple

以上是Python標準庫之sched模組介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn