0

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()

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a simple example. You should consider adding locks.

import threading
import time

def hi( ):
    print('hi')
    mine.start()



class ReusableTime():
    def __init__(self, t, func):
        self._t = t
        self._func = func

    def start(self):
        self._thread = threading.Timer(self._t, self.handler)
        self._thread.start()

    def handler(self):
        self._func()


mine = ReusableTime(2, hi)
mine.start()
time.sleep(100)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.