推迟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.
推荐答案
您需要 threading
模块. /p>
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屋!