Cancellable threading.Timer in Python
You would call the cancel method after you start the timer:
import timeimport threadingdef hello(): print "hello, world" time.sleep(2)t = threading.Timer(3.0, hello)t.start()var = 'something'if var == 'something': t.cancel()
You might consider using a while-loop on a Thread, instead of using a Timer.
Here is an example appropriated from Nikolaus Gradwohl's answer to another question:
import threadingimport timeclass TimerClass(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() self.count = 10 def run(self): while self.count > 0 and not self.event.is_set(): print self.count self.count -= 1 self.event.wait(1) def stop(self): self.event.set()tmr = TimerClass()tmr.start()time.sleep(3)tmr.stop()
I'm not sure if I understand correctly. Do you want to write something like in this example?
>>> import threading>>> t = None>>> >>> def sayHello():... global t... print "Hello!"... t = threading.Timer(0.5, sayHello)... t.start()... >>> sayHello()Hello!Hello!Hello!Hello!Hello!>>> t.cancel()>>>
The threading.Timer
class does have a cancel
method, and although it won't cancel the thread, it will stop the timer from actually firing. What actually happens is that the cancel
method sets a threading.Event
, and the thread actually executing the threading.Timer
will check that event after it's done waiting and before it actually executes the callback.
That said, timers are usually implemented without using a separate thread for each one. The best way to do it depends on what your program is actually doing (while waiting for this timer), but anything with an event loop, like GUI and network frameworks, all have ways to request a timer that is hooked into the eventloop.