Python独立运行多个后台循环
在我的一个项目中,我需要以不同的时间间隔运行三个不同的数据库更新程序函数。 例如,函数1需要每30秒运行一次,函数2需要每60秒运行一次,函数3需要每5分钟运行一次(主要是由于API调用限制) 我一直在尝试用python实现这一点,查找所有可能的解决方案,但似乎找不到任何适合我的用例的方法。我对python很生疏 下面是我使用asyncio的(某种程度上)功能Python独立运行多个后台循环,python,loops,asynchronous,background,task,Python,Loops,Asynchronous,Background,Task,在我的一个项目中,我需要以不同的时间间隔运行三个不同的数据库更新程序函数。 例如,函数1需要每30秒运行一次,函数2需要每60秒运行一次,函数3需要每5分钟运行一次(主要是由于API调用限制) 我一直在尝试用python实现这一点,查找所有可能的解决方案,但似乎找不到任何适合我的用例的方法。我对python很生疏 下面是我使用asyncio的(某种程度上)功能 import asyncio def updater1(url1, url2, time): print(f"Doing my
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()
本身不是异步的。对asyncio.run()
的调用在funcN()
coroutine完成之前不会返回
创建一个顶级协同程序,然后将其他程序作为任务运行:
async def main():
task1 = asyncio.create_task(func1())
task2 = asyncio.create_task(func2())
task3 = asyncio.create_task(func3())
await asyncio.wait([task1, task2, task3])
上述操作启动三个独立的任务,然后等待所有三个任务完成。不要在单个协同程序上使用
asyncio.run()
,因为async.run()
本身不是异步的。对asyncio.run()
的调用在funcN()
coroutine完成之前不会返回
创建一个顶级协同程序,然后将其他程序作为任务运行:
async def main():
task1 = asyncio.create_task(func1())
task2 = asyncio.create_task(func2())
task3 = asyncio.create_task(func3())
await asyncio.wait([task1, task2, task3])
上面列出了三个独立的任务,然后等待这三个任务全部完成