1

I am trying to allow a certain number of seconds for the condition to be met.

timeout = time.time() + 15
while SOMETHING NOT MET:
    time.sleep(1)
    if time.time() > timeout:
       raise Exception
continue

Is this the correct way to allow up to 15s? This doesn't seem to work as expected. Perhaps there is a better/cleaner way.

mysza
  • 31
  • 4
  • Whether this is the best approach or not -- I can't answer. But for this specific approach, the `time.sleep` should go *after* the `timeout` check. – SyntaxVoid Jan 28 '20 at 17:02
  • @SyntaxVoidsupportsMonica I updated it, actually the formatting caused one line not to show up. – mysza Jan 28 '20 at 17:07
  • 2
    How exactly does this not as expected? Please describe more precisely what you expected and what happened instead. – mkrieger1 Jan 28 '20 at 17:09
  • I expect your current version to work fine (despite the fact that it only checks the condition for `timeout-1` instead of `timeout` seconds because you have the `time.sleep` command *before* your `timeout` check but after the condition you care about check. – SyntaxVoid Jan 28 '20 at 17:10
  • @mkrieger1 So what I am trying to achieve is to check if x = y... and while x is not there yet, sleep 1 second, check if timeout was reached (if not, check for x=y) again... and sleep another second up to 15s when timeout would be reached. It seems to move on after way less than 15s – mysza Jan 28 '20 at 17:15

1 Answers1

2

Use signal.alarm, following the example given in the documentation of the signal module.

class TimesUpError(RuntimeException):
    pass


def handler(signum, frame):
    raise TimesUpError


signal.signal(signal.SIGALRM, handler)
signal.alarm(15)
try:
    while SOME_CONDITION:
        time.sleep(1)
except TimesUpError:
    print("Times up, continuing")
finally:
    signal.alarm(0)

Depending on what SOME_CONDITION is, you may be able to use signal.sigtimedwait instead of the loop.

chepner
  • 497,756
  • 71
  • 530
  • 681