#!/usr/bin/python3 # # Simple periodic timer with thread import time from threading import Timer class PeriodicTimer(object): def __init__(self, interval, function, args=[], kwargs={}): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): if self.is_running: self._timer.cancel() self.is_running = False if __name__ == "__main__": pt = time.time() def func(*arg): global pt nt = time.time() print(arg[0], nt - pt) pt = nt tm = PeriodicTimer(0.05, func, args=['time lag=']) print('start timer') tm.start() time.sleep(1) tm.stop() print('stop timer')