2014-09-26 37 views

回答

0

您可以在應該中斷它的函數體中調用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() 
+0

我將如何檢查定時器是否仍在運行或不在interrupt_func()中? – 2014-09-26 02:14:05

+0

@PranavRaj即使計時器已經過期,你也可以調用'cancel',但是你可以調用'timer.finished.is_set()'看到計時器已經被標記爲「已完成」,意味着它已經運行或被取消。 – dano 2014-09-26 02:19:15

+0

請注意根據is_set做出決定。如果它的錯誤,定時器可能隨時觸發,甚至在你的下一行代碼之前。 – tdelaney 2014-09-26 02:49:24