Try the following code:
import asyncio
async def fun1():
#block
await asyncio.sleep(10)
loop = asyncio.get_event_loop()
count = 0
while count < 10:
count += 1
print(count)
try:
fut = asyncio.ensure_future(asyncio.wait_for(fun1(),1))
loop.run_until_complete(fut)
except:
pass
And then inspect the tasks by asyncio.Task.all_tasks(loop=loop)
. You will see that all canceled/finished tasks are still bound to the loop. Instead of closing and getting a new loop, how can I keep the loop and only clear the finished/canceled tasks?
Tasks are bound to loop with weakref, it means they will be garbage collected on next gc run if no references to them exists:
You'll see empty set after gc run.