什麼是背景任務?
BackgroundTasks 是 FastAPI 的內建功能,讓 API 在回傳回應之後,繼續在背景執行耗時的工作,例如寄送通知信、寫入 Log 或更新快取,使用者不需要等待這些操作完成就能收到回應。
BackgroundTasks 基礎語法
- 在路由函式的參數中宣告
background_tasks: BackgroundTasks,FastAPI 會自動注入此物件。 - 呼叫
background_tasks.add_task(函式名稱, 參數1, 參數2)將任務加入佇列,會在回應送出後才執行。 - 背景任務函式同時支援同步(
def)與非同步(async def)兩種寫法。需注意:若使用同步函式執行較耗時的 I/O 操作(如寫入檔案),在高並發情境下仍可能造成執行緒阻塞,建議視情況改用非同步方式處理。 - 可在依賴項(
Depends)中接收BackgroundTasks並新增任務,讓多個路由共用相同的背景邏輯。
import asyncio
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
with open("log.txt", "a", encoding="utf-8") as f:
f.write(f"{message}\n")
async def send_email_notification(email: str, subject: str):
await asyncio.sleep(1) # 模擬非同步寄信操作
print(f"已寄送信件至 {email},主旨:{subject}")
@app.post("/orders/")
async def create_order(item_name: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"新訂單建立:{item_name}")
background_tasks.add_task(
send_email_notification,
"[email protected]",
f"您的訂單《{item_name}》已建立",
)
# 立即回傳,不等待背景任務完成
return {"message": f"訂單《{item_name}》已建立,確認信將於背景寄出"}

















