I noticed the following behavior in the following code (using threading.Timer class):
import threading
def ontimer():
print threading.current_thread()
def main():
timer = threading.Timer(2, ontimer)
timer.start()
print threading.current_thread()
timer.cancel()
if timer.isAlive():
print "Timer is still alive"
if timer.finished:
print "Timer is finished"
if __name__ == "__main__":
main()
The output of the code is:
<_MainThread(MainThread, started 5836)>
Timer is still alive
Timer is finished
As We notice from the output, that the timer object is still alive and finished in the same time.
In fact, I would like to call a similar function hundreds of times, and I wonder whether those “living” timers may affect the performance.
I would like to stop or cancel the timer object in a proper way. Am I doing it right?
Thank you
A
Timeris a subclass of aThreadand its implementation is really simple. It waits the provided time by subscribing to the eventfinished.So when you set the event by
Timer.cancelit is guaranteed that the function does not get called. But it is not guaranteed that the Timer thread will directly continue (and exit).So the point is that the thread of the timer can still be alive after the execution of
cancel, but the function will not get executed. So checking forfinishedis safe, while testing forThread.is_alive(newer API, use this!) is a race condition in this case.Hint: You can verify this by placing a
time.sleepafter callingcancel. Then it will just print: