0

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.

okie
  • 847
  • 6
  • 18
  • The whole point of `sleep` is to pause your program so that it stops executing. You'll need to use something else if you want to interrupt it. – Mark Ransom Dec 11 '20 at 02:03
  • @Mark Ransom I think this is a distinct question to the one you have linked. Here, the OP is asking explicitly about the `time.sleep` function. They're not looking for something which has the same effect as `time.sleep`. And there is an answer to that (multiprocessing or daemons). But I can't give it because the question is closed. – Multihunter Dec 11 '20 at 02:08
  • @Multihunter and if there were an answer to that question, it would be on the linked duplicate. The question is exactly the same. If you have an answer, leave it there. – Mark Ransom Dec 11 '20 at 02:09
  • @Mark Ransom There are answers AROUND it for this particular query. e.g. do they even need to kill the thread? They can use `join(1)` to check if it's thrown an error, and otherwise just leave it going. This would not be a solution to the linked question, but is a solution to this question here. – Multihunter Dec 11 '20 at 02:13

1 Answers1

1

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

xgf115
  • 81
  • 6