3 回答

TA贡献1848条经验 获得超6个赞
你想要一个模块中的Timer对象threading。
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但传递一个函数,有点像这样:
def call_delay(delay, repetitions, func, *args, **kwargs):
for i in range(repetitions):
sleep(delay)
func(*args, *kwargs)
这不会做无限循环,因为这可能导致一个不会死的线程和其他不愉快的行为,如果做得不对。更复杂的方法可能会使用Event基于方法的方法,就像这个方法一样。

TA贡献1802条经验 获得超6个赞
像Javascript这样的异步回调setTimeout需要一个事件驱动的架构。
Python的异步框架,如流行的扭曲有CallLater哪些你想要做什么,但它意味着采用在应用程序中的事件驱动架构。
另一种方法是使用线程并在线程中休眠。Python提供了一个计时器,使等待部分变得容易。但是,当您的线程唤醒并且您的函数执行时,它位于一个单独的线程中,并且必须以线程安全的方式执行任何操作。
添加回答
举报