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

前端 未结 13 1413
挽巷
挽巷 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:12

    I like right2clicky's answer, especially in that it doesn't require a Thread to be torn down and a new one created every time the Timer ticks. In addition, it's an easy override to create a class with a timer callback that gets called periodically. That's my normal use case:

    class MyClass(RepeatTimer):
        def __init__(self, period):
            super().__init__(period, self.on_timer)
    
        def on_timer(self):
            print("Tick")
    
    
    if __name__ == "__main__":
        mc = MyClass(1)
        mc.start()
        time.sleep(5)
        mc.cancel()
    

提交回复
热议问题