shakalaka
shakalaka

Reputation: 171

In python asyncio, is it possible to call another task without waiting for it to finish?

Currently task1 need to wait for task2 to finish. Now I need task2 looks like another thread without affecting the execution of task1, how to achieve that?

async def task2():
    await asyncio.sleep(3)
    print("task2")


async def task1():
    await task2()
    print("task1")
async def main(loop):
    task = loop.create_task(task1())
    await task

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))
    loop.close()

Upvotes: 0

Views: 1294

Answers (1)

kennyvh
kennyvh

Reputation: 2854

You can use asyncio.gather() to run each task that you pass to it concurrently. The code inside each coroutine executes synchronously until it reaches an await keyword where it passes control back to the event loop.

If you want to task2 to be "initiated" by task1, you can use asyncio.Event to wait until an event is set in task2 and set the event in task1.

See the revised example. Both tasks run concurrently using asyncio.gather. But task2 doesn't do anything until the event is set from task1.

import asyncio

async def task2(event):
    print("starting task2")
    await event.wait()
    print("event set")
    await asyncio.sleep(3)
    print("task2 end")


async def task1(event):
    print("starting task1")
    event.set()
    await asyncio.sleep(5)
    print("task1 end")

async def main(loop):
    event = asyncio.Event()

    await asyncio.gather(
        task1(event),
        task2(event)
    )

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))
    loop.close()

I added a few more print statements, a 3 second sleep to task2, and a 5 second sleep to task1. Since they are running concurrently, the output will be:

starting task1
starting task2
event set
task2 end
task1 end

Upvotes: 2

Related Questions