python - 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())
问题是这些任务一个接一个地运行,而我想要实现的是它们彼此独立运行,启动脚本时的开始时间,以及各自的循环时间
非常感谢您对如何做到这一点的任何想法 - 如果您有任何需要我探索的新概念和想法,我愿意接受 :)
解决方案
不要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 完成。
推荐阅读
- java - 使用 Netty 发送的对象消息无法正确解码
- shell - 删除 Markdown 中的 HTML 元素
- jenkins - Jenkins AllView 不叫“All”,不能重命名
- python - 计算文本文件中唯一单词总数的函数
- ruby - Bundler:如何在运行时从当前 Gemfile 中获取组?
- aws-lambda - 有没有办法以编程方式知道 Lambda 函数有多少并发实例正在执行?
- c++ - 如何在 C++ 中从 Eigen MatrixXf 初始化点云
- ruby-on-rails - Rails 中的 Ruby 类扩展在本地声明时有效,从 `/lib/` 导入时返回 `nil`
- python - Python:HTTPS 使用带有请求的代理服务器
- c# - 获取场景中的玩家数量(Unity)