首页 > 解决方案 > Python独立运行多个后台循环

问题描述

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

我一直在尝试在 python 中实现这一点,查找所有可能的解决方案,但我似乎找不到任何适合我的用例的东西。我对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())

问题是这些任务一个接一个地运行,而我想要实现的是它们彼此独立运行,启动脚本时的开始时间,以及各自的循环时间

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

标签: pythonloopsasynchronousbackgroundtask

解决方案


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

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

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 完成。


推荐阅读