from threading import Timer
def startTimer():
t = Timer(10.0, foo, ['hello world', 'tell me more'] )
t.start()
print 'Timer function invoked'
print 'function exit'
def foo(msg, msg2):
print 'foo was executed'
print msg
print msg2
if __name__ == '__main__':
startTimer()
print 'end of program'
I've saved the above code in a file (timer.py), and then typed python timer.py in the shell. But it waited until foo() was executed. Why is this so? What do you call this behaviour/style of execution?
Timer is just a thread and Python waits for all non-daemonic
threads before stopping the interpreter.
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.
Set the_timer.daemon=True
and Python will exit right away instead of waiting for the timer.