[Python] How to get the number of background tasks currently running in a FastAPI application?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    The below run_tasks FastAPI route handler spawns a background task on each HTTP call to the /run-tasks endpoint.

    import asyncio
    import time

    from fastapi import APIRouter
    from starlette.background import BackgroundTasks


    router = APIRouter()


    async def background_task(sleep_time: int, task_id: int):
    print(f"Task {task_id} started")
    await asyncio.sleep(sleep_time) # Simulate a long-running task
    print(f"Task {task_id} completed")


    @router.post("/run-tasks")
    async def run_tasks(background_tasks: BackgroundTasks, sleep_time: int):
    background_tasks.add_task(background_task, sleep_time, int(time.time()))
    print(len(background_tasks.tasks))
    return {"message": "NEW SLEEP query arg background task started"}


    When a SIGTERM signal is sent to the process running this FastAPI app, the following sequence is observed in the logs:

    1. Waiting for background tasks to complete appears.
    2. Afterward, messages like "Task {some_id} completed" are logged.
    3. Finally, the log shows "Waiting for application shutdown", and the application then shuts down.

    Is there a way to get how many background tasks are currently running? I'd like to print the number of remaining tasks after each task completion (i.e., after print(f"Task {task_id} completed")).

    My goal is to see '0' at the end, so that to be sure that all background tasks finished, before application shutdown.

    I understand that a FastAPI app running in Python should wait for all background tasks to finish. However, I want to ensure this also happens when the app runs inside a container within a Kubernetes pod. This is crucial for correctly tuning the terminationGracePeriodSeconds parameter of the pod (see the relevant Termination of Pods documentation).

    Continue reading...

Compartilhe esta Página