我正在考虑实现如下功能:
timeout = 60 second
timer = 0
while (timer not reach timeout):
do somthing
if another thing happened:
reset timer to 0
我的问题是如何实现计时器的东西?多线程或特定的lib?
我希望解决方案基于python内置的lib而不是一些第三方的花哨包。
PS:一个线索应该没问题,你不需要给出整个解决方案。
我不认为你需要线程来描述你所描述的内容。
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