Skip to content
Discussion options

You must be logged in to vote

Hey! Ran into this exact same limitation a while ago. The tricky part is that ASGI itself doesn't actually have a native "server is actively listening" event, which is why lifespan blocks until you yield.

If you just need to kick off a background process right around startup without blocking the server from handling requests, the easiest way is to just drop an asyncio.create_task right before the yield. Since you don't await it, FastAPI will continue starting up:

import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI

async def my_background_job():
    # Optional: give the server a second to bind to the port
    await asyncio.sleep(1) 
    print("Running pos…

Replies: 4 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by rustam-ashurov-mcx
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
3 participants