Waht do you think about my repeated_timer class

Cecil Westerhof Cecil at decebal.nl
Wed Feb 2 14:06:44 EST 2022


I need (sometimes) to repeatedly execute a function. For this I wrote
the below class. What do you think about it?
    from threading  import Timer



    class repeated_timer(object):
        def __init__(self, fn, interval, start = False):
            if not callable(fn):
                raise TypeError('{} is not a function'.format(fn))
            self._fn         = fn
            self._check_interval(interval)
            self._interval   = interval
            self._timer      = None
            self._is_running = False
            if start:
                self.start()

        def _check_interval(self, interval):
            if not type(interval) in [int, float]:
                raise TypeError('{} is not numeric'.format(interval))
            if interval <= 0:
                raise ValueError('{} is not greater as 0'.format(interval))

        def _next(self):
            self._timer = Timer(self._interval, self._run)
            self._timer.start()

        def _run(self):
            self._next()
            self._fn()

        def set_interval(self, interval):
            self._check_interval(interval)
            self._interval = interval

        def start(self):
            if not self._is_running:
                self._next()
                self._is_running = True

        def stop(self):
            if self._is_running:
                self._timer.cancel()
                self._timer      = None
                self._is_running = False

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list