在我的一个项目中,我需要以不同的时间间隔运行三个不同的数据库更新程序函数。 例如,函数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())
问题是这些任务一个接一个地运行,而我试图实现的是它们彼此独立运行,在脚本启动时有一个启动时间,并且各自对应于各自的循环时间
任何关于如何做到这一点的想法都非常感谢-如果您有任何新概念和想法需要我探索,我愿意接受:)
不要在单个协同程序上使用
asyncio.run()
,因为async.run()
本身不是异步的。对asyncio.run()
的调用将不会返回,直到funcN()
协同程序完成创建一个顶级协同程序,然后将其他程序作为任务运行:
上面列出了三个独立的任务,然后等待这三个任务全部完成
相关问题 更多 >
编程相关推荐