我有一个函数列表(1..N),函数i
需要每隔X_i
秒调用一次(X_i会很大,比如1000 + s)。每个X_i
不必是唯一的,即X_i == X_j
。
提供,我生成一个(function_i,X_i)列表如何在将来的适当时间简单地执行这些函数并在调用之间休眠?我之前使用过ApScheduler,但它并行运行任务,我需要一个接一个地运行函数。
我可以编写自己的迭代器,它返回需要执行的当前函数并阻塞直到下一个函数,但如果存在库,我宁愿使用库吗?
编辑:目前N大约是200。
答案 0 :(得分:0)
threading
模块 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])
您可以在线试用here;只需点击运行,然后当你想杀死它时再次点击运行(感谢@DennisMitchell为在线翻译)