Waht do you think about my repeated_timer class
Cecil Westerhof
Cecil at decebal.nl
Wed Feb 2 19:54:54 EST 2022
Cecil Westerhof <Cecil at decebal.nl> writes:
>> (regardless of your OS). The same could be done with this timer; an
>> __exit__ method would make a lot of sense here, and would allow the
>> timer to be used in a with block to govern its execution. (It also
>> isn't really necessary, but if you want a good Pythonic way to show
>> the beginning and end of its use area, a 'with' block is the way to
>> go.)
>
> I will look into that.
Implemented:
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 __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
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._is_running = True
self._next()
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