Python periodic timer interrupt

不羁的心 提交于 2021-02-16 20:46:28

问题


(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!