Python定期定时器中断 [英] Python periodic timer interrupt

查看:109
本文介绍了Python定期定时器中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(如何)如何在Python中激活定期计时器中断?例如,有一个主循环和一个定时器中断,应定期触发该事件:

(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();

我尝试了在在Python中执行定期操作中找到的示例,但它们全都阻止了 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.

推荐答案

任何解决方案都将阻塞main(),或者如果不是进程则生成新线程.

Any solution will either block the main(), or spawn new threads if not a process.

最常用的解决方案是:

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

这篇关于Python定期定时器中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆