0

假设我有以下 python3 程序:

from threading import Timer
import time

thread = Timer(600, print, args=['I am running'])
thread.start()

while threading.activeCount() > 1:
    {{Function to calculate time until thread will start running}}
    print ("Thread will start in %d seconds" % {get above value})
    time.sleep(10)

我正在看的是一个更复杂的多线程,但本质上,对于给定的 Timer 线程,有没有办法检查它以查看它何时运行?

4

1 回答 1

1

我不确定我是否得到你所说的正确,但你可能想要这样的东西:

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 ;-)

于 2013-06-05T09:59:44.330 回答