对于threading.Timer对象,有没有办法在调用start方法后更新计时器时间?
例如
timer = threading.Timer(5, function)
timer.start()
#after calling start method, i want to extend the timer time before expired.
我翻阅了threading.Timer的文档,没有办法。
那么我是否必须调用cancel方法然后再次调用start方法?
最佳答案
Timer
对象确实非常简单:
def Timer(*args, **kwargs):
return _Timer(*args, **kwargs)
class _Timer(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):
"""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()
它只是等待在 threading.Event
对象上调用 wait
并超时,然后运行提供的方法,或者如果 cancel
退出则退出叫。您可以实现自己的 Timer
版本来支持延长等待时间,但默认版本肯定不支持。
关于python - 有什么方法可以扩展 python 中的 threading.Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25142484/