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