定時器 就是隔多長時間去觸發任務執行
指定n秒后執行某操作
Timer如何使用,看Timer源碼
class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event()
Timer()
interval 第一個參數傳 間隔時間
function 傳執行任務的函數 隔了多少秒后執行這個函數
給函數傳參方式 args kwargs
Timer用的是Thread模塊,每啟動一個定時器,啟動一個線程
Thread.__init__(self)
5秒后啟動線程
from threading import Timer def task(name): print("helo %s" %name) t = Timer(5, task, args=("mike",)) # 5秒后啟動線程 t.start()