Python threading.timer - repeat function every 'n' seconds

前端 未结 13 1407
挽巷
挽巷 2020-11-22 09:45

I want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. I\'m not too knowledgeable of how Python threads work and am having diffic

13条回答
  •  情话喂你
    2020-11-22 10:16

    Using timer threads-

    from threading import Timer,Thread,Event
    
    
    class perpetualTimer():
    
       def __init__(self,t,hFunction):
          self.t=t
          self.hFunction = hFunction
          self.thread = Timer(self.t,self.handle_function)
    
       def handle_function(self):
          self.hFunction()
          self.thread = Timer(self.t,self.handle_function)
          self.thread.start()
    
       def start(self):
          self.thread.start()
    
       def cancel(self):
          self.thread.cancel()
    
    def printer():
        print 'ipsem lorem'
    
    t = perpetualTimer(5,printer)
    t.start()
    

    this can be stopped by t.cancel()

提交回复
热议问题