python - 异步迭代器定期滴答

标签 python python-3.x asynchronous python-asyncio

我正在实现一个与 async for 一起使用的异步迭代器,它应该以(大部分)固定间隔返回一个新值。

我们可以用一个简单的时钟来说明这样的迭代器,它会每 ~n 秒递增一个计数器:

import asyncio

class Clock(object):
    def __init__(self, interval=1):
        self.counter = 0
        self.interval = interval
        self.tick = asyncio.Event()
        asyncio.ensure_future(self.tick_tock())

    async def tick_tock(self):
        while True:
            self.tick.clear()
            await asyncio.sleep(self.interval)
            self.counter = self.__next__()
            self.tick.set()

    def __next__(self):
        self.counter += 1
        return self.counter

    def __aiter__(self):
        return self

    async def __anext__(self):
        await self.tick.wait()
        return self.counter

是否有比使用 asyncio.Event 更好或更简洁的方法?不止一个协程将在此迭代器上async for

最佳答案

在我看来,你的方法很好。请注意,自 python 3.6 起,您还可以使用 asynchronous generators :

async def clock(start=0, step=1, interval=1.):
    for i in count(start, step):
        yield i
        await asyncio.sleep(interval)

但是,您将无法在多个协程之间共享它们。您必须在任务中运行时钟并通过异步迭代接口(interface)提供数据,这实际上就是您在代码中所做的。这是一个 possible implementation

关于python - 异步迭代器定期滴答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46934047/

相关文章:

Python 3 : How to search for a list created from a user's input?

python - 当某些列为 datetime.time 类型时,如何按列名对 df 进行切片?

node.js - 让 express.js 从异步回调发送响应

javascript - 如何在 node.js 中创建自定义异步函数

javascript - 是否有 Python、JavaScript 和 CSS 的配置系统?

python - 将文本文件转换为 numpy 数组

python - 你如何在 Django 中动态隐藏表单字段?

python - Ironpython 可以用于并行运行多个 Python 虚拟机实例吗?

python - 如何将 Nonetype 放入列表中?

asynchronous - net/http 中从 1.1.2 到 1.2 的不同行为