asyncio - 多次等待协程(周期性任务)

Arn*_*d H 4 python scheduled-tasks periodic-task python-asyncio

我正在尝试为 asyncio 事件循环创建一个周期性任务,如下所示,但是我收到了“RuntimeError:无法重用已经等待的协程”异常。显然, asyncio 不允许等待与此错误线程中讨论的相同的可等待函数。这就是我尝试实现它的方式:

import asyncio    

class AsyncEventLoop:    

    def __init__(self):
        self._loop = asyncio.get_event_loop()

    def add_periodic_task(self, async_func, interval):
        async def wrapper(_async_func, _interval):
            while True:
                await _async_func               # This is where it goes wrong
                await asyncio.sleep(_interval)
        self._loop.create_task(wrapper(async_func, interval))
        return

    def start(self):
        self._loop.run_forever()
        return
Run Code Online (Sandbox Code Playgroud)

由于我的 while 循环,相同的可等待函数 (_async_func) 将在中间有一个睡眠间隔的情况下执行。我从如何使用 asyncio 定期执行函数中获得了实现周期性任务的灵感.

从上面提到的错误线程,我推断 RuntimeError 背后的想法是为了让开发人员不会意外地等待同一个协程两次或更多次,因为协程将被标记为完成并产生 None 而不是结果。有没有办法可以不止一次等待相同的功能?

And*_*sky 6

似乎您将异步函数(协程函数)与协程(这些异步函数产生的值)混淆了。

考虑这个异步函数:

async def sample():
    await asyncio.sleep(3.14)
Run Code Online (Sandbox Code Playgroud)

您正在传递其调用的结果:add_periodic_task(sample(), 5)

相反,您应该传递异步函数对象本身:add_periodic_task(sample, 5),并在您的包装器中调用它:

while True:
    await _async_func()
    await asyncio.sleep(_interval)
Run Code Online (Sandbox Code Playgroud)