在python中推迟函数 [英] Postponing functions in python
问题描述
在 JavaScript 中,我习惯于能够调用稍后执行的函数,就像这样
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.
我不知道如何在 Python 中实现类似的功能.我可以使用睡眠
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()
但这会阻止其他代码的执行.(实际上,在我的情况下,阻塞 Python 本身并不是问题,但我无法对方法进行单元测试.)
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.)
我知道线程是为不同步执行而设计的,但我想知道是否存在类似于 setTimeout
或 setInterval
的更简单的东西.
I know threads are designed for out-of-sync execution, but I was wondering whether something easier, similar to setTimeout
or setInterval
exists.
推荐答案
你想要一个 Timer
对象来自 threading
模块.
You want a Timer
object from the threading
module.
from threading import Timer
from time import sleep
def foo():
print "timer went off!"
t = Timer(4, foo)
t.start()
for i in range(11):
print i
sleep(.5)
如果你想重复,这里有一个简单的解决方案:不要使用 Timer
,只需使用 Thread
而是传递一个类似这样的函数:
If you want to repeat, here's a simple solution: instead of using Timer
, just use Thread
but pass it a function that works somewhat like this:
def call_delay(delay, repetitions, func, *args, **kwargs):
for i in range(repetitions):
sleep(delay)
func(*args, *kwargs)
这不会造成无限循环,因为如果做得不好,可能会导致线程不会死亡和其他令人不快的行为.更复杂的方法可能使用基于 Event
的方法,像这样.
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.
这篇关于在python中推迟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!