首页 > 解决方案 > 如何永远运行异步函数(Python)

问题描述

如何使用 asyncio 并永远运行该功能。我知道有,run_until_complete(function_name)但是如何使用run_forever如何调用异步函数?

async def someFunction():
    async with something as some_variable:
        # do something

我不确定如何启动该功能。

标签: pythonpython-3.xasynchronouspython-asyncio

解决方案


run_forever并不意味着异步函数会神奇地永远运行,这意味着循环将永远运行,或者至少直到有人调用loop.stop(). 要从字面上永远运行异步函数,您需要创建一个执行此操作的异步函数。例如:

async def some_function():
    async with something as some_variable:
        # do something

async def forever():
    while True:
        await some_function()

loop = asyncio.get_event_loop()
loop.run_until_complete(forever())

这就是为什么run_forever()不接受参数,它不关心任何特定的协程。典型的模式是loop.create_task在调用之前添加一些使用或等效的协程run_forever()。但即使是一个不运行任何任务并且闲置的事件循环也很有用,因为另一个线程可以调用asyncio.run_coroutine_threadsafe它并让它工作。


推荐阅读