如何在async任务完成前做一些工作?

问题描述 投票:0回答:1

我是新来的,想学习一下 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())

我的想法很简单:

  1. 创建一个异步任务 check_it().并等待它。
  2. 用一个 while 循环来检查任务是否完成。
  3. 如果 task.done() 返回 True,打破 while loop.然后退出脚本。

如果我的问题是重复的,请标记我的问题.谢谢!

python python-3.x python-asyncio
1个回答
2
投票

试试 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())
© www.soinside.com 2019 - 2024. All rights reserved.