Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threading.Timer()

i have to write a program in network course that is something like selective repeat but a need a timer. after search in google i found that threading.Timer can help me, i wrote a simple program just for test how threading.Timer work that was this:

import threading  def hello():     print "hello, world"  t = threading.Timer(10.0, hello) t.start()  print "Hi" i=10 i=i+20 print i 

this program run correctly. but when i try to define hello function in a way that give parameter like:

import threading  def hello(s):     print s  h="hello world" t = threading.Timer(10.0, hello(h)) t.start()  print "Hi" i=10 i=i+20 print i 

the out put is :

hello world Hi 30 Exception in thread Thread-1: Traceback (most recent call last):   File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner     self.run()   File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 726, in run     self.function(*self.args, **self.kwargs) TypeError: 'NoneType' object is not callable 

i cant understand what is the problem! can any one help me?

like image 269
sandra Avatar asked May 16 '13 03:05

sandra


People also ask

What is threading timer?

Threading. Timer, which executes a single callback method on a thread pool thread at regular intervals.

What is timer () in Python?

A timer in Python is a time-tracking program. Python developers can create timers with the help of Python's time modules. There are two basic types of timers: timers that count up and those that count down.

How does threading timer work Python?

Threading in Python Timer() starts following the delay defined as an argument. The Timer class thus calls itself delaying the execution of the following operation by the same amount of time specified.

How do you make a timer thread in Python?

Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly. Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.


1 Answers

You just need to put the arguments to hello into a separate item in the function call, like this,

t = threading.Timer(10.0, hello, [h]) 

This is a common approach in Python. Otherwise, when you use Timer(10.0, hello(h)), the result of this function call is passed to Timer, which is None since hello doesn't make an explicit return.

like image 128
tom10 Avatar answered Sep 23 '22 03:09

tom10