python中的非阻塞事件调度

时间:2014-11-28 14:29:10

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

是否可以安排一个函数在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代码。有没有办法以非阻塞方式安排功能或使用'某些功能触发它? os?

1 个答案:

答案 0 :(得分:9)

你可以"重新安排"该事件通过在回调函数中启动另一个Timer

import threading

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

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