how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve.
while true:
test = 0
if test == 5:
break
test = test - 1
This code throws me in an endless loop.
long start_time = System. currentTimeMillis(); long wait_time = 10000; long end_time = start_time + wait_time; while (System. currentTimeMillis() < end_time) { //.. } Should do the trick.
An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a break statement is found. You can stop an infinite loop with CTRL + C .
Stopping the looping. The while statement will repeatedly execute the loop statement or code block while the true/false expression is true. To stop the looping, something needs to happen to change the true/false expression to false.
terminate() function will terminate foo function. p. join() is used to continue execution of main thread. If you run the above script, it will run for 10 seconds and terminate after that.
Try the following:
import time
timeout = time.time() + 60*5 # 5 minutes from now
while True:
test = 0
if test == 5 or time.time() > timeout:
break
test = test - 1
You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1)
at the beginning or end of the loop body).
You do not need to use the while True:
loop in this case. There is a much simpler way to use the time condition directly:
import time
# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
test = 0
if test == 5:
break
test -= 1
Try this module: http://pypi.python.org/pypi/interruptingcow/
from interruptingcow import timeout
try:
with timeout(60*5, exception=RuntimeError):
while True:
test = 0
if test == 5:
break
test = test - 1
except RuntimeError:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With