(How) can I activate a periodic timer interrupt in Python? For example there is a main loop and a timer interrupt, which should be triggered periodically:
def handler(): # do interrupt stuff def main(): init_timer_interrupt(<period>, <handler>); while True: # do cyclic stuff if __name__ == "__main__": main(); I have tried the examples found at Executing periodic actions in Python, but they are all either blocking the execution of main(), or start spawning new threads.
1 Answer
Any solution will either block the main(), or spawn new threads if not a process.
The most commonly used solution is:
threading.Timer( t, function).start() It can be used recursively, one simple application is:
import threading import time class Counter(): def __init__(self, increment): self.next_t = time.time() self.i=0 self.done=False self.increment = increment self._run() def _run(self): print("hello ", self.i) self.next_t+=self.increment self.i+=1 if not self.done: threading.Timer( self.next_t - time.time(), self._run).start() def stop(self): self.done=True a=Counter(increment = 1) time.sleep(5) a.stop() this solution will not drift over the time