如何在不等待 python 完成的情况下执行异步任务?

How to do async task without waiting for it to finish in python?

我有这样的程序

task_2_running = False

async def task2():
    task_2_running = True
    await do_something()
    task_2_running = False

async def main():
    while True:
        x = await task1()
        do_something(x)
        if some_condition(x) and not task_2_running:
            #Do task2() but don't wait until it finished

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

如何调用 task2() 以便循环继续而不等待 task2() 完成,并且 task2() 仍会在将来的某个时间完成?

您可以使用 asyncio.create_task,示例如下:

test.py:

import time

task_2_running = False

async def task1():
    time.sleep(3)

async def task2():
    print("task2 run")
    task_2_running = True
    await asyncio.sleep(5)
    task_2_running = False
    print("task2 finish")

async def main():
    while True:
        print("main run")
        x = await task1()
        if not task_2_running:
            print("create task2")
            #Do task2() but don't wait until it finished
            asyncio.create_task(task2())
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

执行:

$ python3 test.py
main run
create task2
task2 run
main run
create task2
task2 run
task2 finish
main run
create task2
task2 run
^C

从执行中可以看出,在task2 run之后,main run并没有等待task2 finish,而是继续运行下一个循环打印另一个main run.

顺便说一句,asyncio.create_task 仅适用于 python3.7 及更高版本,对于 < python3.7,您可能需要使用 asyncio.ensure_future(),请参阅 this

async def coro():
    ...

# In Python 3.7+
task = asyncio.create_task(coro())
...

# This works in all Python versions but is less readable
task = asyncio.ensure_future(coro())
...