Tuesday, May 27, 2025

How to perform Background task in FastAPI?

from fastapi import FastAPI, BackgroundTasks

import time

app = FastAPI()

def background_task(name: str):

    print(f"Start processing for {name}")

    time.sleep(5)  # simulate a long task

    print(f"Finished processing for {name}")


@app.post("/process/")

async def process_request(name: str, background_tasks: BackgroundTasks):

    background_tasks.add_task(background_task, name)

    return {"message": f"Request received. Processing {name} in the background."}


If You Need More Advanced Background Processing

If your task is CPU-intensive or you need retries, scheduling, or better queue management, consider:


Celery (with Redis/RabbitMQ) — for distributed task queues.

RQ (Redis Queue) — simpler alternative to Celery.

APScheduler — for scheduled background tasks.

ThreadPoolExecutor / ProcessPoolExecutor — for internal background threading.


No comments:

Post a Comment