【问题标题】:Non blocking event scheduling in pythonpython中的非阻塞事件调度
【发布时间】:2015-01-27 05:45:34
【问题描述】:

是否可以在 python 中安排一个函数在每 xx 毫秒执行一次,而不阻塞其他事件/不使用延迟/不使用睡眠?

What is the best way to repeatedly execute a function every x seconds in Python? 解释了如何使用 sched 模块执行此操作,但该解决方案会在等待时间(如睡眠)阻塞整个代码执行。

像下面给出的简单调度是非阻塞的,但调度只工作一次——重新调度是不可能的。

from threading import Timer
def hello():
    print "hello, world" 

t = threading.Timer(10.0, hello)
t.start() 

我在安装了 Raspbian 的 Raspberry pi 中运行 python 代码。有没有办法以非阻塞方式调度函数或使用操作系统的“某些功能”触发它?

【问题讨论】:

    标签: python timer raspberry-pi scheduled-tasks nonblocking


    【解决方案1】:

    您可以通过在回调函数中启动另一个 Timer 来“重新安排”事件:

    import threading
    
    def hello():
        t = threading.Timer(10.0, hello)
        t.start()
        print "hello, world" 
    
    t = threading.Timer(10.0, hello)
    t.start() 
    

    【讨论】:

    • @RodrigoRodrigues 是的
    • 你如何阻止它
    猜你喜欢
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    相关资源
    最近更新 更多