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