I need a way to interrupt a long sleep
function, without splitting it into multiple sleep(1)
or any shorter time. The way to stop it can be any possible way, including threading
.
For deeper explanation, what i am trying to do is testing sleep
's limit, so I am writing a automate program repeat calling sleep
. Catching all OverflowError
raised by sleep
.
What I've tried:
from time import sleep
import threading
def test(x):
try:
sleep(x) #kill the thread or anyway to interrupt the sleep AFTER execution
except:
return 1
addigit = True
t = ""
while True:
if addigit:
t= t+"9"
th = threading.Thread(target = test,args=(int(t),))
print("running:"+t)
ex = th.start()
#threading.Lock.release() not working
#th._stop()
print(ex)
if ex:
if addigit:
addigit = False
print("len:"+len(t))
Notice that the code is incomplete, I only need the way of stopping sleep
right after executed it. (I only need the exception raised by sleep
, I don't want to wait for years to know the answer)
The flag or stop statement check(if stop:exit
) way won't work, because they are executed after sleep.
I would instead call wait() on a threading.Event object. It's what I typically do for a problem like this.
Here is an example: https://stackoverflow.com/a/38828735/14804613