Home > Mobile >  how to check if timer is expired in python?
how to check if timer is expired in python?

Time:11-04

I am having some questions related to python timer. Hope someone can give some suggestions on that. :)

I would like when the timer is expired after 20sec, then it printout a string and exit(2), I look into some example hence, I have written the first example below, the problem for that is after timeout, event I have written sys.exit(2) in the function, it will not exit it with 2, but with exit code 0 instead.

import sys
import threading

def application_timeout():
    print("The application is timeout\n")
    sys.exit(2)

timer = threading.Timer(20.0, application_timeout)
timer.start()

Below is my second example, I am managed to make the code exit 2, but the code doesn't look as nice. Just wondering can someone give me a suggestion on that?

import sys import threading

def application_timeout():
    print("The application is timeout\n")

timer = threading.Timer(20.0, application_timeout)
timer.start()
while(timer.is_alive() == True):
    timerstillalive = False

if(timerstillalive == False):
    print("Timer is expired")
    sys.exit(2)

CodePudding user response:

Two ideas:


easy thing would be:

while timer.is_alive():
     pass

print("Timer is expired")
sys.exit(2)

That is just nicer looking, but does the same thing


funnier method:

pip install waiting

a nice library to wait until condition is true

wait(lambda: (False if timer.is_alive() else True), timeout_seconds=1, waiting_for="Timer to be expired")

CodePudding user response:

The second one is good enough, but you can simplify it by checking timer.is_alive() directly.

def application_timeout():
    print("The application is timeout\n")

timer = threading.Timer(20.0, application_timeout)
timer.start()
while(timer.is_alive() == True):
   pass
print("Timer is expired")
sys.exit(2)

CodePudding user response:

It's happening because Thread's run method ignores SystemExit. From threading documentation

If the run() method raises an exception, threading.excepthook() is called to handle it. By default, threading.excepthook() ignores silently SystemExit.

You want to exit 2 when the application_timeout function returns. In that case, you can use Event,

event = threading.Event()

def application_timeout():
    print("The application is timeout\n")
    event.set()

timer = threading.Timer(20.0, application_timeout)
timer.start()

event.wait()
sys.exit(2)
  • Related