Python中的非阻塞事件调度

5

有没有可能在Python中安排一个函数每xx毫秒执行一次,而不会阻塞其他事件/不使用延迟或睡眠?这里介绍了如何使用sched模块实现,但该方案会像sleep一样阻塞整个代码执行。

下面提供的简单调度是非阻塞的,但是仅适用于一次性调度 - 不支持重新调度。

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

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

我正在树莓派上运行安装有Raspbian系统的Python代码。有没有办法以非阻塞的方式调度函数或使用操作系统的“某些功能”来触发它?

2个回答

11

你可以通过在回调函数中启动另一个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 是的,它可以。 - A---
你如何停止它? - Nic Scozzaro

0

如果你不能使用threading,比如在一些代码生成器中你的自由度很小,那么可以考虑下面定义的elapsed函数作为替代方案。我已经用这个函数测试了三个非阻塞任务:onetwo并行执行,然后执行three

#!/usr/bin/env python3
# timer.py

from time import time #, sleep
from pprint import pprint

t = dict()


def elapsed(name: str, duration: float):
    if name in t:
        return (time() >= t[name])
    else:
        t[name] = time() + duration
        return False


if __name__ == "__main__":
    finished = False
    fone = ftwo = fthree = True
    start = time()
    qt = 0
    print(f"Start at {start:0.2f} : one for 1s and two for 2s together, then three for 3s")
    while not finished:
        if len(t) > qt: #int(time() * 10) % 10 == 0:
            pprint(t)
            qt = len(t) #sleep(0.01)
        one = elapsed("one", 1)
        two = elapsed("two", 2)
        three = False
        if one and fone:
            print(f"one finished in {time() - start:0.2f} seconds")
            fone = False
        if two and ftwo:
            print(f"two finished in {time() - start:0.2f} seconds")
            ftwo = False
        if one and two:
            three = elapsed("three", 3)
        if three and fthree:
            print(f"three finished in {time() - start:0.2f} seconds")
            fthree = False
        if three:
            finished = True

输出:

 ./timer.py
Start at 1656828388.84 : one for 1s and two for 2s together, then three for 3s
{'one': 1656828389.8441286, 'two': 1656828390.84413}
one finished in 1.00 seconds
two finished in 2.00 seconds
{'one': 1656828389.8441286, 'three': 1656828393.844173, 'two': 1656828390.84413}
three finished in 5.00 seconds

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接