python key press to interrupt time.sleep()

Viewed 5802

I have a program that spends a lot of time asleep in an endless loop, it checks in with another system API every 6 hours, and if there are changes does some stuff, if not goes back to sleep.

Without listing all the code, its pretty simple; I have

while True:
    do some stuff
    time.sleep(21600)

The only way to break this is with CTRL+C, but that seems ugly, is there a way to make another keypess interrupt the time.sleep() and use a graceful sys.exit()?

2 Answers

i am not writing any code, but here is my idea... instead of a big sleep time like sleep(21600) make a loop that runs 21600*1000 times and sleep for a millisecond, and in that loop keep listening for keyboard interrupt or keypress. the code is going to be ugly so i suggest use abstraction.

P.S. why 21600*1000 and not "21600 and sleep for a sec", a sec is not to precise. The probability that you'll press keyboard interrupt while sleep(1) is active is more than if you use milli or micro second.

Related