Waht do you think about my repeated_timer class

Marco Sulla Marco.Sulla.Python at gmail.com
Wed Feb 2 16:09:02 EST 2022


You could add a __del__ that calls stop :)

On Wed, 2 Feb 2022 at 21:23, Cecil Westerhof via Python-list
<python-list at python.org> wrote:
>
> 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
> --
> https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list