独立循环运行异步

时间:2018-01-24 18:29:11

标签: python python-3.x

是否可以独立于另一个循环运行异步while循环?

我在以下示例代码

中分离了我遇到的问题,而不是实际的代码
import asyncio, time

class Time:
    def __init__(self):
        self.start_time = 0

    async def dates(self):
        while True:
            t = time.time()
            if self.start_time == 0:
                self.start_time = t
            yield t
            await asyncio.sleep(1)

    async def printer(self):
        while True:

            print('looping') # always called

            await asyncio.sleep(self.interval)

    async def init(self):
        async for i in self.dates():
            if i == self.start_time: 
                self.interval = 3 
                await self.printer()
            print(i) # Never Called

loop = asyncio.get_event_loop()
t = Time()
loop.run_until_complete(t.init())

有没有办法让打印功能独立运行,每次调用print(i)

它应该做的是print(i)每秒,每3秒调用self.printer(i)

本质上,self.printer是一个单独的任务,不需要经常调用,只需每隔x秒(在本例中为3)。

在JavaScript中,解决方案是做类似的事情 setInterval(printer, 3000);

编辑:理想情况下,如果调用条件或停止函数,也可以取消/停止self.printer

2 个答案:

答案 0 :(得分:2)

JavaScript asyncio的{​​{1}}等价物为setTimeout

asyncio.ensure_future

答案 1 :(得分:0)

您希望将self.printer()协程注册为单独的任务;将其传递给asyncio.ensure_future()而不是直接等待它:

asyncio.ensure_future(self.printer())

通过将协同程序传递给asyncio.ensure_future(),您可以将它放在循环之间切换的事件列表中,因为每个事件都要等待进一步的工作完成。

通过该更改,您的测试代码输出:

1516819094.278697
looping
1516819095.283424
1516819096.283742
looping
1516819097.284152
# ... etc.

任务是多线程场景中的asyncio等效线程。

相关问题