Skip to content

BackgroundTasks blocks entire FastAPI application #11210

Answered by H-G-11
mostopalove asked this question in Questions
Discussion options

You must be logged in to vote

Your issue is linked to the way Python handles asynchronous code, not FastAPI itself.

For instance, this works as expected:

from asyncio import sleep
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()


async def testing():
    print('I am going to block whole application')
    await sleep(60)
    print('I am alive again after 60 seconds of blocking')


@app.get("/check")
def check():
    return 'It works'


@app.get("/task")
def add_task(background_tasks: BackgroundTasks):
    background_tasks.add_task(testing)
    return 'Task was added'

As you can see, the only difference is that now, your async background task is really asynchronous (asyncio.sleep and not time.sleep), it w…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@mostopalove
Comment options

@mastizada
Comment options

Answer selected by mostopalove
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
4 participants