I need to wait until a certain condition/equation becomes True in a asynchronous function in python. Basically it is a flag variable which would be flagged by a coroutine running in asyncio.create_task(). I want to await until it is flagged in the main loop of asyncio. Here’s my current code:
JavaScript
x
16
16
1
import asyncio
2
flag = False
3
4
async def bg_tsk():
5
await asyncio.sleep(10)
6
flag = True
7
8
async def waiter():
9
asyncio.create_task(bg_tsk())
10
await asyncio.sleep(0)
11
# I find the below part unpythonic
12
while not flag:
13
await asyncio.sleep(0.2)
14
15
asyncio.run(waiter())
16
Is there any better implementation of this? Or is this the best way possible? I have tried using ‘asyncio.Event’, but it doesnt seem to work with ‘asyncio.create_task()’.
Advertisement
Answer
Using of asyncio.Event
is quite straightforward. Sample below.
Note: Event should be created from inside coroutine for correct work.
JavaScript
1
17
17
1
import asyncio
2
3
4
async def bg_tsk(flag):
5
await asyncio.sleep(3)
6
flag.set()
7
8
9
async def waiter():
10
flag = asyncio.Event()
11
asyncio.create_task(bg_tsk(flag))
12
await flag.wait()
13
print("After waiting")
14
15
16
asyncio.run(waiter())
17