欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python標準庫sched模塊使用指南

 更新時間:2017年07月06日 08:53:52   作者:j_hao104  
這篇文章主要介紹了Python標準庫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, 這里為秒);
# 優(yōu)先級(兩個事件在同一時間到達的情況);
# 觸發(fā)的函數;
# 函數參數;
s.enter(10, 1, print_time, ())

# 運行
s.run()
print time.time()

if __name__ == '__main__':
print_some_times()

看到的輸出結果,隔5秒中執(zhí)行第一個事件,隔10秒后執(zhí)行第二個事件:

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) # 阻塞主線程,等待調度程序執(zhí)行完畢,再執(zhí)行后面內容
print time.time()

if __name__ == '__main__':
print_some_times()

Scheduler對象方法

scheduler對象擁有下面這些方法或屬性:

scheduler.enterabs(time, priority, action, argument)

加入一個事件, time 參數應該是一個與傳遞給構造函數的 timefunc 函數的返回值相兼容的數值類型。在同一時間到達的事件將按照 priority 順序執(zhí)行。

執(zhí)行事件其實就是執(zhí)行 action(argument) 。argument必須是一個包含 action 參數的序列。

返回值是一個事件,它可以用于稍后取消事件(請參見 cancel() )。

scheduler.enter(delay, priority, action, argument)

安排一個事件來延遲 delay 個時間單位。除了時間外,其他參數、含義和返回值與 enterabs() 的值相同。其實內部 enterabs 就是用來被 enter 調用。

scheduler.cancel(event)

從隊列中刪除事件。如果事件不是當前隊列中的事件,則該方法將跑出一個 ValueError 。

scheduler.empty()

判斷隊列是否為空。

scheduler.run()

運行所有預定的事件。這個函數將等待(使用傳遞給構造函數的 delayfunc() 函數),然后執(zhí)行事件,直到不再有預定的事件。

任何 action 或 delayfunc 都可以引發(fā)異常。在這兩種情況下,調度器將保持一個一致的狀態(tài)并傳播異常。如果一個異常是由 action 引起的,就不會再繼續(xù)執(zhí)行 run() 。

scheduler.queue

只讀屬性,返回一個即將到達的事件列表(按到達事件排序),每個事件都是有 time 、 priority 、 action 、 argument 組成的 namedtuple 。

相關文章

最新評論