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:
Waiting for background tasks to complete. appears.
Afterward, messages like Task {some_id} completed are logged.
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 to be sure all background tasks finished before application shutdown.
I want to see “0” at the end, indicating that all background tasks have completed before the application shutdown.
I understand that a FastAPI app running with 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. Docs