2013-11-09 171 views
0

我想實現像下面的功能:Python的計時器計時

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

我的問題是如何實現計時器的東西?多線程或特定的lib?

我希望解決方案是基於python內置的lib而不是某些第三方的花哨軟件包。

在此先感謝。

PS:線索應該沒問題,你不需要給出整個解決方案。

回答

1

我不認爲你需要線程爲你所描述的。

import time 

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

在這裏,你檢查每一個迭代。

你需要一個線程的唯一原因是如果你想在一個迭代的中間中停止,如果事情花費太長時間。

+0

哈,這聽起來很正確的。我只是陷入了一個錯誤的方向。謝啦 –

0

我用下面的習慣:

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