Python独立运行多个后台循环

标签 python loops asynchronous background task

在我的一个项目中,我需要以不同的时间间隔运行三个不同的数据库更新程序函数。 例如,函数一需要每 30 秒运行一次,函数二需要每 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() 协程完成之前不会返回

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

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 个任务完成。

关于Python独立运行多个后台循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071640/

相关文章:

javascript - for 循环中的 setTimeout

javascript - "this"在原型(prototype)函数中返回未定义

c# - WPF : webbrowser call async silverlight method synchronously in javascript

python - 在 org 模式下将字符串参数从表传递到代码块

python-3.x - 组合使用 itertools 和 zip 从两个不同长度的列表创建字典时出现问题

python - IPython 支持 ctypes 吗?

python - 从文件中读取以获取并打印 JSON 数据

angularjs - Angularjs ng-src 从函数调用异步加载图像

python - 跟踪 scala 中方法的执行情况

python - gensim 是如何快速找到最相似的单词的?