小编dwp*_*est的帖子

快速精确的Python重复计时器

我需要快速准确地从列表中发送重复消息.一个列表需要每100ms发送一次消息,窗口为+/- 10ms.我尝试使用下面的代码,但问题是计时器等待100毫秒,然后所有计算都需要完成,使计时器落在可接受的窗口之外.

简单地减少等待是一个混乱,不可靠的黑客.如果在循环期间编辑列表,则消息循环周围会有一个Lock.

关于如何让python在100ms左右发送消息的想法?谢谢

from threading import Timer
from threading import Lock

class RepeatingTimer(object):
    def __init__(self,interval, function, *args, **kwargs):
        super(RepeatingTimer, self).__init__()
        self.args = args
        self.kwargs = kwargs
        self.function = function
        self.interval = interval
        self.start()

    def start(self):
        self.callback()

    def stop(self):
        self.interval = False

    def callback(self):
        if self.interval:
            self.function(*self.args, **self.kwargs)
            Timer(self.interval, self.callback, ).start()

def loop(messageList):
    listLock.acquire()
    for m in messageList:
        writeFunction(m)
    listLock.release()


MESSAGE_LIST = [] #Imagine this is populated with the messages
listLock = Lock()
rt = RepeatingTimer(0.1,loop,MESSAGE_LIST)
#Do other stuff after …
Run Code Online (Sandbox Code Playgroud)

python multithreading timer repeat

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

multithreading ×1

python ×1

repeat ×1

timer ×1