Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否有方法检查线程。计时器何时运行?_Python_Python 3.x - Fatal编程技术网

Python 是否有方法检查线程。计时器何时运行?

Python 是否有方法检查线程。计时器何时运行?,python,python-3.x,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 wi

假设我有以下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)

我看到的是更复杂的一点,有多个线程,但本质上,对于给定的计时器线程,是否有任何方法可以检查它以查看它计划何时运行?

我不确定我是否正确理解您所说的内容,但您可能希望这样:

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)
这里的想法是重新创建一个计时器线程,该线程将倒计时直到时间结束,并在执行此操作时更新“超时值”。结束后,将启动线程事件。所以当你这样做的时候:

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

你知道线程池吗?不…我只是用threading获取所有打开的线程。enumerate()。在没有线程池的情况下使用多个线程不是一个坏习惯。我最终实现了一些类似的东西,但我将所有内容都封装在字典中(伪代码):{startTime:2030-10-10 05:00:00,thread:Timer(在启动时间之前的秒数,函数运行)}。