I used the code from the below link to manually call the shutdown events
https://github.com/fastapi/fastapi/discussions/11872#discussioncomment-10134866
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
for on_shutdown in app.router.on_shutdown:
await on_shutdown()
app = FastAPI(lifespan=lifespan)
async def get_profiler_result():
print("On shutdown has been called")
app.add_event_handler("shutdown", get_profiler_result)
Caveat: This is just a hack. also see