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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With