如何在 Python 中实现定时函数



我正在考虑实现如下函数:

timeout = 60 second
timer = 0
while (timer not reach timeout):
    do somthing
    if another thing happened:
         reset timer to 0

我的问题是如何实现计时器的东西?多线程还是特定库?

我希望该解决方案基于 python 内置库,而不是一些第三方花哨的包。

我认为你不需要线程来描述你所描述的。

import time
timeout = 60
timer = time.clock()
while timer + timeout < time.clock():
    do somthing
    if another thing happened:
        timer = time.clock()

在这里,您可以检查每次迭代。

您需要线程的唯一原因是,如果某些事情花费的时间太长,如果您想在迭代过程中停止。

我使用以下成语:

from time import time, sleep
timeout = 10 # seconds
start_doing_stuff()
start = time()
while time() - start < timeout:
    if done_doing_stuff():
        break
    print "Timeout not hit. Keep going."
    sleep(1) # Don't thrash the processor
else:
    print "Timeout elapsed."
    # Handle errors, cleanup, etc

最新更新