Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implment timeout for a while loop

Tags:

python

time

I have a while loop

while somecondition:
    dostuff

(Sorry. It is hard to give an executable example as this is part of a larger project).

Most of the time the condition is met after a short while and the loop expires. But sometimes the condition will never be met. How can I best catch such cases? Is a timer the best option? How can I implement it best?

like image 741
Aguy Avatar asked Mar 26 '26 16:03

Aguy


2 Answers

You can use a timeout using SIGALRM. Here's a little program that demonstrates it.

import sys

import time
import signal


class TimeoutError(Exception):
    pass

def _sig_alarm(sig, tb):
    raise TimeoutError("timeout")

def main(argv):
    timeout = 7
    signal.signal(signal.SIGALRM, _sig_alarm)
    try:
        signal.alarm(timeout)
        while True:
            print("sleeping...")
            time.sleep(1)
    except TimeoutError:
        pass
    print("Out of loop.")



main(sys.argv)

This sets up a signal handler that simply raises a custom exception (but you can use any), and then catches it.

like image 174
Keith Avatar answered Mar 28 '26 04:03

Keith


wait for an hour example

from datetime import timedelta
delete_TO = 1
wait_until = datetime.now() + timedelta(hours=delete_TO)
break_loop = False
while not break_loop:
     do-your loop-stuff
     if wait_until < datetime.now() or somecondition:
          break_loop = True

(edited: wait_until must be smaller than datetime.now() )

like image 27
Ohad the Lad Avatar answered Mar 28 '26 05:03

Ohad the Lad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!