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 userNế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.
BackgroundTasks runs a task after the response has been sent, fitting lightweight work such as sending email, writing audit logs or non-critical webhooks. It is not a replacement for a real queue.
Example:
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 userIf the task needs retry, scheduling, durability or long execution, use Celery/RQ/Arq, a message broker or a workflow engine.