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

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

    In the interest of providing a correct answer using Timer as the OP requested, I'll improve upon swapnil jariwala's answer:

    from threading import Timer
    
    
    class InfiniteTimer():
        """A Timer class that does not stop, unless you want it to."""
    
        def __init__(self, seconds, target):
            self._should_continue = False
            self.is_running = False
            self.seconds = seconds
            self.target = target
            self.thread = None
    
        def _handle_target(self):
            self.is_running = True
            self.target()
            self.is_running = False
            self._start_timer()
    
        def _start_timer(self):
            if self._should_continue: # Code could have been running when cancel was called.
                self.thread = Timer(self.seconds, self._handle_target)
                self.thread.start()
    
        def start(self):
            if not self._should_continue and not self.is_running:
                self._should_continue = True
                self._start_timer()
            else:
                print("Timer already started or running, please wait if you're restarting.")
    
        def cancel(self):
            if self.thread is not None:
                self._should_continue = False # Just in case thread is running and cancel fails.
                self.thread.cancel()
            else:
                print("Timer never started or failed to initialize.")
    
    
    def tick():
        print('ipsem lorem')
    
    # Example Usage
    t = InfiniteTimer(0.5, tick)
    t.start()
    

提交回复
热议问题