0
我在Python中设置了一个定时器,可以说20秒,但是如果调用另一个函数,那么计时器应该中断。当执行一个函数时打破线程。定时器
有没有什么办法可以用Python的threading.Timer
来执行?
我在Python中设置了一个定时器,可以说20秒,但是如果调用另一个函数,那么计时器应该中断。当执行一个函数时打破线程。定时器
有没有什么办法可以用Python的threading.Timer
来执行?
您可以在应该中断它的函数体中调用timer.cancel()
。
def some_func():
print "Some function that runs after a timeout"
def interrupt_func():
timer.cancel() # some_func will no longer be called
# other stuff
timer = threading.Timer(20, some_func)
time.sleep(10)
interrupt_func()
我将如何检查定时器是否仍在运行或不在interrupt_func()中? – 2014-09-26 02:14:05
@PranavRaj即使计时器已经过期,你也可以调用'cancel',但是你可以调用'timer.finished.is_set()'看到计时器已经被标记为“已完成”,意味着它已经运行或被取消。 – dano 2014-09-26 02:19:15
请注意根据is_set做出决定。如果它的错误,定时器可能随时触发,甚至在你的下一行代码之前。 – tdelaney 2014-09-26 02:49:24