Python 独立运行多个后台循环



在我的一个项目中,我需要以不同的时间间隔运行三个不同的数据库更新程序函数。 例如,函数 1 需要每 30 秒运行一次,函数 2 需要每 60 秒运行一次,函数 3 需要每 5 分钟运行一次(特别是由于 API 调用限制(。

我一直在尝试在 python 中实现这一目标,查找所有可能的解决方案,但我似乎找不到任何适合我的用例的东西。我对蟒蛇相当新鲜。

这是我(有点(拥有的,使用 asyncio。

import asyncio
def updater1(url1, url2, time):
print(f"Doing my thing here every {time} seconds")
def updater2(url1, url2, time):
print(f"Doing my thing here every {time} seconds")
def updater3(url, time):
print(f"Doing my thing here every {time} seconds")

async def func1():
updater1(rankUrl, statsUrl, 30)
await asyncio.sleep(30)

async def func2():
updater2(rankUrl, statsUrl, 60)
await asyncio.sleep(60)

async def func3():
updater3(url, 300)
await asyncio.sleep(300)

# Initiate async loops
while True:
asyncio.run(func1())
asyncio.run(func2())
asyncio.run(func3())

问题是这些任务一个接一个地运行,而我试图实现的是它们彼此独立运行,在启动脚本时具有开始时间,并且对应于它们各自的循环时间。

非常感谢关于如何做到这一点的任何想法 - 如果您对新概念和想法有任何探索:),我愿意接受新概念和想法

不要在单个协程上使用asyncio.run(),因为async.run()本身不是异步的。funcN()协程完成之前,对asyncio.run()的调用不会返回。

创建一个顶级协程,然后将其他协程作为任务运行:

async def main():
task1 = asyncio.create_task(func1())
task2 = asyncio.create_task(func2())
task3 = asyncio.create_task(func3())
await asyncio.wait([task1, task2, task3])

上面启动三个独立的任务,然后等待所有 3 个任务完成。

最新更新