是否可以独立于另一个循环运行异步 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 也可以被取消/停止
The 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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)