是否有可能独立于另一个运行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也将能够被取消/停止
最佳答案
与JavaScript的asyncio
等效的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())
关于python - 独立运行while循环时异步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48429306/