I can't wrap my head around how to use aynchio. Can you please just help me fix this issue. Assume I have some IO task which takes 8 seconds that I put in the coroutine task(). I want to run an infinite loop and perform this take every 5 seconds without blocking my code.
import asyncio
async def task():
print('starting task')
await asyncio.sleep(8)
print('finished task')
async def main():
count = 0
while True:
print(count)
if count % 5 == 0:
print('running task')
await task()
count += 1
await asyncio.sleep(1)
asyncio.run(main())
From my understanding of the docs, when I perform await
inside the task
coroutine, it should go back to executing main
but this does not happen. What am I doing wrong here? My output is
0
running task
starting task
finished task
1
2
3
4
5
running task
starting task
finished task
6
7
8
9
10
Your issue is you're awaiting the coroutine, which does what it says on the box: It stops anything from proceeding until it completes (to say it doesn't go back to main isn't quite right either. It does, just later than you wanted). Spinning it out to another unawaited task will let it "run in the background"
import asyncio
async def task():
print('starting task')
await asyncio.sleep(8)
print('finished task')
async def main():
count = 0
while True:
print(count)
if count % 5 == 0:
print('running task')
asyncio.create_task(task())
count += 1
await asyncio.sleep(1)
asyncio.run(main())
Gives me, which I think is what you want
0
running task
starting task
1
2
3
4
5
running task
starting task
6
7
finished task
8
9
10
running task
starting task
11
12
finished task
13
14