Search code examples
pythonexecution

why does this python script wait till the timer thread is executed?


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?


Solution

  • 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.

    from the docs

    Set the_timer.daemon=True and Python will exit right away instead of waiting for the timer.