有没有办法检查线程何时.Timer将运行?

时间:2013-06-05 09:34:33

标签: python python-3.x

假设我有以下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线程,有没有办法检查它以查看它何时被安排运行?

1 个答案:

答案 0 :(得分:0)

我不确定我说得对你说的是什么,但你可能想要这样的东西:

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)

这里的想法是重新创建一个Timer计数线程,该计时器线程将在时间结束前倒计时,并在执行此操作时更新“超时值”。当它结束时,它启动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 ; - )

相关问题