Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
deostroll Avatar asked Dec 25 '10 18:12

deostroll


People also ask

How do I stop a countdown in Python?

Python timer functions To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time. sleep(secs).

What is threading timer in Python?

Introduction to Python Threading Timer. The timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period. Python's threading. Timer() starts after the delay specified as an argument within the threading.

What is a timer thread?

Timer Object. The Timer is a subclass of Thread. Timer class represents an action that should be run only after a certain amount of time has passed. A Timer starts its work after a delay, and can be canceled at any point within that delay time period. Timers are started, as with threads, by calling their start() method ...

How do I run a specific time thread in Python?

However, if you want a particular function to wait for a specific time in Python, we can use the threading. Timer() method from the threading module. We'll show a simple example, which schedules a function call every 5 seconds.


1 Answers

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.

like image 150
Jochen Ritzel Avatar answered Sep 20 '22 23:09

Jochen Ritzel