自己摸索才能真正理解python的threading.Timer()定時器的用法。
首先讓我們看下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() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set()
舉個例子:
import time from threading import Timer def fun(): print("hello, world") if __name__=='__main__': t = Timer(5, fun) # 超過5秒,執行fun函數 t.start() sum = 0 for i in range(6): sum = i+1 time.sleep(1) # 等待了6次超過Timer中的5秒 t.cancel() # 結束后將timer取消掉