Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I stop a while loop after n amount of time?

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.

like image 759
Adilicious Avatar asked Nov 08 '12 16:11

Adilicious


People also ask

How do you stop a while loop after a time?

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.

How do you stop an infinite while loop?

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 .

What causes a while loop to stop?

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.

How do I stop a Python script after a certain time?

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.


3 Answers

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).

like image 93
Andrew Clark Avatar answered Oct 13 '22 04:10

Andrew Clark


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
like image 52
Petr Krampl Avatar answered Oct 13 '22 06:10

Petr Krampl


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
like image 43
andrefsp Avatar answered Oct 13 '22 04:10

andrefsp