Reputation: 1506
I am thinking to implement a function like below:
timeout = 60 second
timer = 0
while (timer not reach timeout):
do somthing
if another thing happened:
reset timer to 0
My question is how to implement the timer stuff? Multiple thread or a particular lib?
I hope the solution is based on the python built-in lib rather than some third-part fancy package.
Upvotes: 0
Views: 217
Reputation:
I use the following idiom:
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
Upvotes: 0
Reputation: 83205
I don't think you need threads for what you have described.
import time
timeout = 60
timer = time.clock()
while timer + timeout < time.clock():
do somthing
if another thing happened:
timer = time.clock()
Here, you check every iteration.
The only reason you would need a thread is if you wanted to stop in the middle of an iteration if something was taking too long.
Upvotes: 1