我不确定我是否得到你所说的正确,但你可能想要这样的东西:
from threading import Thread
import time
thread = Timer(600, print, args=['I am running'])
thread.start()
class ThreadTimeoutLauncher(Thread):
def __init__(self, timeout, cb, *args, **kwarg):
super(Thread, self).__init__()
self.timeout = timeout
self._cb = cb
self._args = args
self._kwarg = kwarg
def run():
print ("Thread will start in %d seconds" % self.timeout)
while self.timeout > 0:
time.sleep(1)
self.timeout -= 1
self.cb(*self._args, **self._kwarg)
这里的想法是重新创建一个计时器线程,该线程将倒计时直到时间结束,并在这样做时更新“超时值”。当它结束时,它会启动 Thread 事件。所以当你这样做时:
def foo():
print "Thread launched!"
t = ThreadTimeoutLauncher(600, foo)
t.start()
while True:
time.sleep(0.5)
print "thread will be launched in: %d sec." % t.timeout
也可以从 Timer 继承并更改 Timer 的 run() 方法,但这意味着UTSL ;-)