是否可以独立于另一个循环运行异步 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(打印机, 3000);
编辑:如果条件或停止函数被调用,理想情况下 self.printer 也可以被取消/停止
请您参考如下方法:
asyncio 相当于 JavaScript 的 setTimeout 将是 asyncio.ensure_future:
import asyncio
async def looper():
for i in range(1_000_000_000):
print(f'Printing {i}')
await asyncio.sleep(0.5)
async def main():
print('Starting')
future = asyncio.ensure_future(looper())
print('Waiting for a few seconds')
await asyncio.sleep(4)
print('Cancelling')
future.cancel()
print('Waiting again for a few seconds')
await asyncio.sleep(2)
print('Done')
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
