Home > Net >  How to stop the sleep() function
How to stop the sleep() function

Time:09-27

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')

CodePudding user response:

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()
  • Related