Search code examples
pythontimerreset

Resettable Timer object implementation python


I need a timer in Python which i can reset (timer.reset()). I already have a periodic timer. Is there a library with such a timer?

class MyTimer(threading.Timer):
    def __init__(self, t):
        threading.Thread.__init__(self)
        self.__event = threading.Event()
        self.__stop_event = threading.Event()
        self.__intervall = t

    def run(self):
        while not self.__stop_event.wait(self.__intervall):
            self.__event.set()

    def clear(self):
        self.__event.clear()

    def is_present(self):
        return self.__event.is_set()

    def cancel(self):
        self.__stop_event.set()

Solution

  • Here's an example that implements a reset method to "extend" the timer by the original interval. It uses an internal Timer object rather than subclassing threading.Timer.

    from threading import Timer
    import time
    
    
    class ResettableTimer(object):
        def __init__(self, interval, function):
            self.interval = interval
            self.function = function
            self.timer = Timer(self.interval, self.function)
    
        def run(self):
            self.timer.start()
    
        def reset(self):
            self.timer.cancel()
            self.timer = Timer(self.interval, self.function)
            self.timer.start()
    
    
    if __name__ == '__main__':
        t = time.time()
        tim = ResettableTimer(5, lambda: print("Time's Up! Took ", time.time() - t, "seconds"))
        time.sleep(3)
        tim.reset()
    

    Output:

    Time's Up! Took 8.011203289031982 seconds