Vasily Sobolev
Vasily Sobolev

Reputation: 41

Asyncio wait_for one function to end, or for another

My code has 2 functions:

async def blabla():
    sleep(5)

And

async def blublu():
    sleep(2)

asyncio.wait_for as I know can wait for one function like this: asyncio.wait_for(blublu(), timeout=6) or asyncio.wait_for(blublu(), timeout=6) What I wan't to do, is to make asyncio wait for both of them, and if one of them ends faster, proceed without waiting for the second one. Is it possible to make so? Edit: timeout is needed

Upvotes: 0

Views: 587

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

Use asyncio.wait with the return_when kwarg:

# directly passing coroutine objects in `asyncio.wait` 
# is deprecated since py 3.8+, wrapping into a task
blabla_task = asyncio.create_task(blabla())
blublu_task = asyncio.create_task(blublu())

done, pending = await asyncio.wait(
    {blabla_task, blublu_task},
    return_when=asyncio.FIRST_COMPLETED
)

# do something with the `done` set

Upvotes: 1

Related Questions