问题
(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:
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
来源:https://stackoverflow.com/questions/52722864/python-periodic-timer-interrupt