16.2.7. Timer Objects
# The timer class was contributed by Itamar Shtull-Trauring
def Timer(*args, **kwargs):
"""Factory function to create a Timer object.
Timers call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
return _Timer(*args, **kwargs)
翻译:Timer工厂函数,返回一个定时器对象,定时器对象负责调用函数,在指定的时间之后。
真正的定时器类:_Timer
class _Timer(Thread): #继承Thread类
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}): #重写构造函数
Thread.__init__(self) #调用父类构造函数
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event() #内部事件类,用来定时作用
def cancel(self): #自定义cancel方法,取消定时器执行
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self): #重写run方法
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
演示:
import threading
def hello():
print 'hello world!!!'
ti=threading.Timer(interval=3,function=hello)
ti.start()
运行结果:
C:\Python27\python.exe E:/pythonproj/基础练习/t8.py
hello world!!!
Process finished with exit code 0