Cơ BảnFastAPI iconFastAPI

BackgroundTasks trong FastAPI dùng cho việc gì?

BackgroundTasks chạy task sau khi response đã gửi, phù hợp cho việc nhẹ như gửi email, ghi audit log hoặc gọi webhook không critical. Nó không thay thế queue thật.

Ví dụ:

python
@app.post("/signup")
async def signup(payload: Signup, tasks: BackgroundTasks):
    user = await create_user(payload)
    tasks.add_task(send_welcome_email, user.email)
    return user

Nếu task cần retry, scheduling, durability hoặc chạy lâu, nên dùng Celery/RQ/Arq, message broker hoặc workflow engine.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI