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

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

    Improving a little on Hans Then's answer, we can just subclass the Timer function. The following becomes our entire "repeat timer" code, and it can be used as a drop-in replacement for threading.Timer with all the same arguments:

    from threading import Timer
    
    class RepeatTimer(Timer):
        def run(self):
            while not self.finished.wait(self.interval):
                self.function(*self.args, **self.kwargs)
    

    Usage example:

    def dummyfn(msg="foo"):
        print(msg)
    
    timer = RepeatTimer(1, dummyfn)
    timer.start()
    time.sleep(5)
    timer.cancel()
    

    produces the following output:

    foo
    foo
    foo
    foo
    

    and

    timer = RepeatTimer(1, dummyfn, args=("bar",))
    timer.start()
    time.sleep(5)
    timer.cancel()
    

    produces

    bar
    bar
    bar
    bar
    

提交回复
热议问题