1. 程式人生 > >python 定時服務模塊

python 定時服務模塊

都是 bili int sch 文檔 IT argument 時間 刪除

python定時任務使用方法如下:

import sched
shelder = sched.scheduler(time.time, time.sleep)
shelder.enter(2, 0, print_time, ())
shelder.run()

執行順序說明如下:

1、創建一個定時任務執行的實例 2、將定時任務插入到執行隊列中 3、啟動定時任務 enter方法的參數說明: 第一個參數是在任務啟動多少秒後執行 第二個參數是任務優先級 第三個參數是要執行的方法 第四個參數是方法要傳進去的參數,沒有的話直接使用() 實例1:順序執行
import time
import sched
def print_time(): print now the time is:,time.time() def do_some_times(): print begin time:,time.time() shelder.enter(2, 0, print_time, ()) shelder.enter(2, 0, print_time, ()) shelder.enter(5, 1, print_time, ()) shelder.run() print end time:,time.time() do_some_times()

運行結果:

begin time: 1525682354.85

now the time is: 1525682356.86

now the time is: 1525682356.86

now the time is: 1525682359.86

end time: 1525682359.86

這裏後面的時間都是一樣的是因為表示的是加入到隊列時間

在涉及到多線程的問題時使用上面的方法就會引入線程安全的限制,官方手冊上也做了充分的說明,具體如下:

In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead. 最終的意思就是使用threading的Timer進行替代 實例2:線程安全的
from threading import Timer
import time
def print_time():
    print now the time is:,time.time()
def print_times():
    print begin time is:,time.time()
    Timer(5, print_time,(())).start()
    Timer(10, print_time,(())).start()
    time.sleep(2)
    print end time is:,time.time()
    
print_times()

運行結果:

begin time is: 1525682440.55

end time is: 1525682442.55

now the time is: 1525682445.55

now the time is: 1525682450.55

實例3:任務自調度

from threading import Timer
import time

counttimes=3
def print_time():
    global counttimes
    if counttimes > 0:
        print now the time is %d,%f: % (counttimes,time.time())
        Timer(5, print_time,(())).start()
        counttimes -= 1

def print_times():
    print begin time is:,time.time()
    Timer(5, print_time,(())).start()
    time.sleep(2)
    print end time is:,time.time()
print_times()

運行結果:

begin time is: 1525682594.3

end time is: 1525682596.3

now the time is 3,1525682599.300889:

now the time is 2,1525682604.302403:

now the time is 1,1525682609.302912:

附錄

常用schelder方法:

scheduler.enterabs(time, priority, action, argument) scheduler.enter(delay, priority, action, argument) scheduler.cancel(event) 刪除一個任務事件 scheduler.empty() 任務隊列是否為空 scheduler.run() 啟動任務,執行下一個任務時會進行等待 scheduler.queue 任務隊列 參考文檔: https://docs.python.org/2/library/sched.html

python 定時服務模塊