在单个线程中每n秒调度一次事件(python)

2024-03-28 22:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列事件和它们的轮询时间。 [{“A”:5,“B”:7,“C”:9}]

所以事件A(某个函数)需要每x秒调用一次, 在上面的例子中,一个函数需要从现在起每隔5秒钟调用一次(不只是一次,而是不断重复)

从现在起每隔7秒就需要调用B函数,以此类推。你知道吗

在第35秒时,A和B都将被调用(考虑到函数A和B几乎同时返回假定printf())

有标准算法吗?如果没有任何关于如何做到这一点的指示?你知道吗

这条线上有些东西(但不起作用)

import threading
class A():
    def A():
        printf "A"
    def B():
        printf "B"
    def __init__(self, *args, **kwargs):
        self.iteration = 1
    def execute(self,arr):
        for key in arr[0]:
            print key, arr[key]
            t1 = threading.Timer(arr[key], key).start()
            t2 = threading.Timer(arr[key], key).start()


A().execute([{"A":5,"B",7}])

Tags: key函数selfexecute标准def时间事件
2条回答

我的版本基本上与El Shotz'相同,但我防止计数器变得非常大(如果不是精度错误的话,最终会表现为内存泄漏):

from functools import reduce
from operator import mul
from time import sleep

def a():
    print("I am A")

def b():
    print("I am B")

def c():
    print("I am C")

my_dict ={a:5,b:7,c:9}

numerator = reduce(mul, my_dict.values(), 1)
while True:
    for counter in range(numerator):
        for k, v in my_dict.items():
            if counter%v == 0:
                k()
        sleep(1)

numerator是所有等待值的乘积,因此当counter循环完成时,我们在0处同步,所有东西都在正确的位置重新开始。你知道吗

这有一个小问题,就是如果任何函数需要很长时间来执行,我们的内部时钟就会开始漂移。如果你绝对需要在第二个运行所有的东西,那么你需要做一些更复杂的事情来确保你等待的时间是正确的。你知道吗

首先,应该将计时器列表转换为字典,函数为键,间隔为值。然后,您可以集成一个计数器,它以秒为单位计算每次睡眠(1)呼叫后的时间。或者,您可以使用datetime模块来查找从现在到启动时间之间的时间差。你知道吗

import time    
def a():
    pass
def b():
    pass
timers = {a:9, b:3}
time_counter = 0
while True:
    time.sleep(1)
    time_counter += 1
    for function in timer.keys():
        if time_counter % timer[function] is 0:
            function()

很明显,你必须改变我写的代码一点,但原则应该是类似的

相关问题 更多 >