In JavaScript I am used to being able to call functions to be executed at a later time, like this
function foo() {
alert('bar');
}
setTimeout(foo, 1000);
This does not block the execution of other code.
I do not know how to achieve something similar in Python. I can use sleep
import time
def foo():
print('bar')
time.sleep(1)
foo()
but this will block the execution of other code. (Actually in my case blocking Python would not be a problem in itself, but I would not be able to unit test the method.)
I know threads are designed for out-of-sync execution, but I was wondering whether something easier, similar to setTimeout or setInterval exists.
You want a
Timerobject from thethreadingmodule.If you want to repeat, here’s a simple solution: instead of using
Timer, just useThreadbut pass it a function that works somewhat like this:This won’t do infinite loops because that could result in a thread that won’t die and other unpleasant behavior if not done right. A more sophisticated approach might use an
Event-based approach, like this one.