question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] async BackgroundTasks run in the foreground

See original GitHub issue

Describe the bug async BackgroundTasks are not running as background tasks. My response blocks until the task finishes.

To Reproduce Steps to reproduce the behavior:

  1. Create a file run.py with contents
from fastapi import FastAPI, BackgroundTasks

import time
import asyncio

app = FastAPI()

async def sleep_for_10_seconds():
    start = time.time()
    while True:
        now = time.time()
        if now - start > 10: 
            break
        asyncio.sleep(1)
    print(time.time(), 'slept for 10 seconds')


@app.get("/")
async def read_root(background_tasks: BackgroundTasks):
    print(time.time(), 'read_root')
    background_tasks.add_task(sleep_for_10_seconds)
    return {"Hello": "World"}
  1. Run with uvicorn run:app --reload
  2. Run curl http://localhost:8000

Expected behavior {"Hello": "World"} returns immediately. Instead it takes 10 seconds.

Environment:

  • macOS
  • fastapi==0.27.0
  • uvicorn==0.8.4
  • Python 3.6.6 :: Anaconda, Inc.

Additional context I originally thought this problem was confined to asyncio.ensure_future() in #403, but I’m getting the same behavior with fastapi.BackgroundTasks.

sync tasks return immediately (i.e. don’t define with async).

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
dmontagucommented, Jul 24, 2019

@euri10 @ebanner I think I found the problem:

async def sleep_for_10_seconds():
    start = time.time()
    while True:
        now = time.time()
        if now - start > 10:
            break
        await asyncio.sleep(1)  # <-- HERE (was missing the await)
    print(time.time(), 'slept for 10 seconds')

After making this change, it seems to behave properly.

0reactions
gary-x0pacommented, May 19, 2021

I realised if you replaced asyncio.sleep with time.sleep it blocks the request anyone has a reason why async background tasks does not run in separate thread and how to potentially solve this problem

Read more comments on GitHub >

github_iconTop Results From Across the Web

Run async tasks using Background T… - Apple Developer
I've got an iOS app that performs a series of operations when initialized and when a refresh is performed. In short, that app...
Read more >
Background task and Foreground process crash with error ...
When I try to trigger the background task from Lifecycle events, both the foreground and the background process crash with error code 1....
Read more >
Run async function on background thread? - Stack Overflow
Imagine someone writing await Task.Delay(-1) , and then be surprised that the next line of code is never reached. This person needs urgently ......
Read more >
Asynchronous Background Processing using .NET Tasks
Creating an asynchronous background processing handler that leverages the .NET Task framework to replace the old BackgroundWorker.
Read more >
Background Tasks - FastAPI
Create a function to be run as the background task. It is just a standard function that can receive parameters. It can be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found