我是新来的,想学习一下 asyncio
.我不知道如何描述我的问题.但这里有一个最小的例子。
import asyncio
async def work():
await asyncio.sleep(3)
async def check_it():
task = asyncio.create_task(work())
await task
while True:
if task.done():
print("Done")
break
print("Trying...")
asyncio.run(check_it())
我的想法很简单:
check_it()
.并等待它。while
循环来检查任务是否完成。task.done()
返回 True
,打破 while
loop.然后退出脚本。如果我的问题是重复的,请标记我的问题.谢谢!
试试 asyncio.wait
或使用 asyncio.sleep
. 否则,你的程序会输出很多,而不会有一些停顿。
import asyncio
async def work():
await asyncio.sleep(3)
async def check_it():
task = asyncio.create_task(work())
# "await" block until the task finish. Do not do here.
timeout = 0 # Probably the first timeout is 0
while True:
done, pending = await asyncio.wait({task}, timeout=timeout)
if task in done:
print('Done')
# Do an await here is favourable in case any exception is raised.
await task
break
print('Trying...')
timeout = 1
asyncio.run(check_it())