With the code below, FINISHED coroutines seem never to be removed from the async loop. After every request from a client, an additional coroutine is added to the loop. What is the best way to remove finished coroutines and therefore not running into out of memory problems?
import uvicorn
import asyncio
from loguru import logger
app = FastAPI()
terminate = False
@app.get("/")
async def root():
return {"message": "Hello World"}
async def print_coroutines():
global terminate
while not terminate:
coroutines = asyncio.Task.all_tasks()
logger.debug('Total number of coroutines: ' + str(len(coroutines)))
for coro in coroutines:
logger.debug(coro)
await asyncio.sleep(2)
@app.on_event("startup")
async def startup_event():
asyncio.get_event_loop().create_task(print_coroutines())
@app.on_event("shutdown")
async def shutdown_event():
global terminate
terminate = True
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=5000)
Console output after opening one browser window:
Total number of coroutines: 5
<Task pending coro=<Server.startup.<locals>.handler() running
<Task pending coro=<Server.serve() running
<Task finished coro=<Server.startup.<locals>.handler() done
<Task pending coro=<LifespanOn.main() running
<Task pending coro=<print_coroutines() running