Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python theading.Timer: how to pass argument to the callback?

Tags:

python

timer

My code:

    import threading  def hello(arg, kargs):     print arg  t = threading.Timer(2, hello, "bb") t.start()  while 1:     pass 

The print out put is just:

b 

How can I pass a argument to the callback? What does the kargs mean?

like image 343
Bin Chen Avatar asked Dec 11 '10 07:12

Bin Chen


People also ask

How do I use the thread timer 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.

How do I add a delay to a thread in Python?

Adding a Python sleep() Call With time.sleep() The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify. If you run this code in your console, then you should experience a delay before you can enter a new statement in the REPL.

How do you end a timer 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).

How do I cancel thread timer?

Once created, the thread must be started by calling the start() function which will begin the timer. If we decide to cancel the timer before the target function has executed, this can be achieved by calling the cancel() function.


1 Answers

Timer takes an array of arguments and a dict of keyword arguments, so you need to pass an array:

import threading  def hello(arg):     print arg  t = threading.Timer(2, hello, ["bb"]) t.start()  while 1:     pass 

You're seeing "b" because you're not giving it an array, so it treats "bb" an an iterable; it's essentially as if you gave it ["b", "b"].

kwargs is for keyword arguments, eg:

t = threading.Timer(2, hello, ["bb"], {arg: 1}) 

See http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html for information about keyword arguments.

like image 82
Glenn Maynard Avatar answered Nov 04 '22 09:11

Glenn Maynard