Python 循环调度程序-在适当的时间定期调用函数

Python 循环调度程序-在适当的时间定期调用函数,python,Python,我有一个函数列表(1..N),需要每隔X_I秒调用函数I(X_I会很大,比如1000+s)。每个X_i不必是唯一的,即X_i==X_j 如果提供,我将生成一个(function_I,X_I)列表,如何在将来的适当时间执行这些函数并在调用之间休眠?我以前使用过ApScheduler,但它并行运行任务,我需要一个接一个地运行函数 我可以编写自己的迭代器,它返回需要执行的当前函数并阻塞到下一个函数,但如果存在库,我宁愿使用库 编辑:目前N大约为200。线程化模块 threading模块允许您启动一个新

我有一个函数列表(1..N),需要每隔
X_I
秒调用函数
I
(X_I会很大,比如1000+s)。每个
X_i
不必是唯一的,即
X_i==X_j

如果提供,我将生成一个(function_I,X_I)列表,如何在将来的适当时间执行这些函数并在调用之间休眠?我以前使用过ApScheduler,但它并行运行任务,我需要一个接一个地运行函数

我可以编写自己的迭代器,它返回需要执行的当前函数并阻塞到下一个函数,但如果存在库,我宁愿使用库

编辑:目前N大约为200。

线程化
模块
threading
模块允许您启动一个新线程,它不会受到其他线程的
sleep
语句的影响。这需要
N
线程,因此,如果
N
非常庞大,请告诉我,我将尝试考虑其他解决方案

您可以创建
N
线程,并将每个线程设置为定时循环,如下所示:

import threading, time

def looper(function, delay): # Creates a function that will loop that function
    def inner(): # Will keep looping once invoked
        while True:
            function() # Call the function; you can optionally add args
            time.sleep(delay) # Swap this line and the one before it to wait before running rather than after
    return inner # The function that should be called to start the loop is returned

def start(functions, delays): # Call this with the two lists to start the loops
    for function, delay in zip(functions, delays): # Goes through the respective pairs
        thread = threading.Thread(target = looper(function, delay)) # This thread will start the looper
        thread.start()

start([lambda: print("hi"), lambda: print("bye")], [0.2, 0.3])

你可以在网上试试;只需点击run,然后在想要杀死它时再次点击run(感谢@DennisMitchell提供的在线翻译)

嗨,谢谢你的回答。我不希望函数并行运行的原因是每个函数都将数据插入数据库。我正在使用SQLAlchemy,我认为它将同时处理插入,但同时我希望避免这种复杂性。也许我不应该为此担心。@S5不确定-这可能会导致比赛条件出现问题。我将尝试创建一个不需要并行的方法,因为我已经更新了我的问题。N现在大约是200。@s5s好的。这可能不会给现代计算机带来很多问题,但我正在研究更好的解决方案。延迟都是整数吗?