2014-09-26 39 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