How to stop the sleep() function

Question:

I have an infinite loop that immediately goes to sleep for one minute and then displays a message, but the problem is that when I stop the loop, the sleep() function works and the message is displayed at the end. Is it possible to reset sleep() after stopping the loop immediately?

from time import sleep
i = int(input())
flag = True
while flag:
    if i < 0:
        flag = False
    sleep(60)
    print('Hello, world')
Asked By: Kanashii12

||

Answers:

you will likely need to implement a "special interruptable sleep" … something like this could be a naive implementation that "works"

def do_something():
    pass
    
class Program:
    flag = True
    def stoppable_sleep(self,t):
        endTime = time.time() + t
        while time.time() < endTime and self.flag:
             time.sleep(0.1)
    def mainloop(self):
        while flag:
            do_something()
            self.stoppable_sleep(60)
        print("Done...")
    def stop(self):
        self.flag = False

p = Program()
threading.Timer(5,p.stop)
p.mainloop()
Answered By: Joran Beasley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.