跳至主要內容
模組 2:多 Agent 2 / 6
中階 S08 Background Tasks Async

背景任務

把長時間的命令、subagents 與整個 session 放到背景執行,並在完成時依任務通知採取行動。

2026年3月20日 18 分鐘閱讀
已校驗 課程最近校驗: 2026年10月21日

你將學到什麼

有些操作需要時間。執行完整測試套件可能需要 30 秒。建構 Docker 映像可能需要 2 分鐘。部署到預備環境可能需要 5 分鐘。沒有背景任務的話,Claude Code 只能閒置等每個命令跑完,你也只能跟著等。

完成後,你將了解:

  • 為什麼某些任務應該在背景執行
  • 背景任務的生命週期:啟動、監控、通知
  • 任務通知如何回報完成狀態
  • 何時使用前景 vs. 背景執行
  • 如何在等待時持續進行有用的工作
  • 何時該把命令、subagent 或整個 session 放到背景

問題是什麼

考慮這個情境:

User: "Run the full test suite, then fix any failing tests."

Without background tasks:
  AI: Runs test suite...
      ████████░░░░░░░░░░░░ 45%
      ... (you wait 90 seconds) ...
      ████████████████████ 100%
  AI: "3 tests failed. Let me fix them."

這 90 秒被浪費了。AI 本可以在讀取測試檔案、分析可能的失敗模式,或準備修復方案。相反,它阻塞在同步呼叫上,什麼都沒做。

這就是閒置等待問題。同步執行意味著 AI 一次只能做一件事,即使當前操作不需要它的關注。

如何運作

前景 vs. 背景

Claude Code 支援兩種執行模式:

Foreground (blocking):
  ┌──────────┐     ┌──────────┐     ┌──────────┐
  │  Start   │────►│  Wait... │────►│  Result  │
  │  command │     │  (idle)  │     │  ready   │
  └──────────┘     └──────────┘     └──────────┘
  Time: ============================|

Background (non-blocking):
  ┌──────────┐     ┌──────────────────────────────┐
  │  Start   │────►│  Continue working...          │
  │  command │     │  Write code, read files, plan │
  └──────────┘     │  ...                          │
                   │  ◄── Notification: "Done!"    │
                   └──────────────────────────────────┘
  Time: ====|  (productive work fills the gap)

關鍵區別:在背景模式下,AI 立即取回控制權,可以在操作執行時做其他工作。

背景任務生命週期

每個背景任務遵循三個階段:

┌───────────────────────────────────────────────────────┐
│               Background Task Lifecycle               │
│                                                       │
│  Phase 1: LAUNCH                                      │
│  ┌───────────────────────────────────────────┐        │
│  │  Bash call with run_in_background: true   │        │
│  │  → command starts as its own process      │        │
│  │  → Claude gets a task ID + output file    │        │
│  │  → Claude continues with the next action  │        │
│  └───────────────────────────────────────────┘        │
│                                                       │
│  Phase 2: MONITOR                                     │
│  ┌───────────────────────────────────────────┐        │
│  │  The process runs independently           │        │
│  │  → stdout/stderr go to the output file    │        │
│  │  → exit status is tracked                 │        │
│  │  → no Claude attention required           │        │
│  └───────────────────────────────────────────┘        │
│                                                       │
│  Phase 3: NOTIFY                                      │
│  ┌───────────────────────────────────────────┐        │
│  │  Process ends: success, failure, or stop  │        │
│  │  → Claude Code sends a task notification  │        │
│  │  → an idle session starts a new turn      │        │
│  │  → Claude reads the output file and acts  │        │
│  └───────────────────────────────────────────┘        │
│                                                       │
└───────────────────────────────────────────────────────┘

啟動背景任務

run_in_background 參數可在 Bash 工具中使用:

{
  "type": "tool_use",
  "name": "Bash",
  "input": {
    "command": "npm test",
    "description": "Run full test suite",
    "run_in_background": true
  }
}

當這個執行時:

  1. 測試套件在獨立的程序中開始執行
  2. Claude 會立即拿回一個背景任務 ID,以及輸出正在寫入的檔案路徑
  3. AI 的下一個動作可以是任何事 — 它不必等待

與前景呼叫(預設)比較:

{
  "type": "tool_use",
  "name": "Bash",
  "input": {
    "command": "npm test",
    "description": "Run full test suite"
  }
}

這會阻塞直到 npm test 完成或達到逾時(預設兩分鐘;Claude 最多可要求十分鐘)。達到逾時時,Claude Code 會把命令移到背景,而不是終止它;以 sleep 開頭的命令例外。

你也可以自己把工作移到背景:按 Ctrl+B 把執行中的命令移到背景(在 tmux 內要按兩次)。執行 /tasks 可以列出目前 session 的背景工作,並停止其中任何一項。

任務通知

背景任務完成、失敗或被停止時,Claude Code 會送給 Claude 一則任務通知。通知帶有狀態、簡短摘要與輸出檔案路徑;Claude 用 Read 工具讀取完整輸出。(獨立的 TaskOutput 工具已在 Claude Code 2.1.277 移除。)Claude Code 會標明這則通知不是來自你,因此 Claude 不會把它當成指示或核准。

Turn N:
  AI launches background task: "npm test"
  AI continues: reads files, writes code...

Turn N+1 (the notification starts it if the session is idle):
  [Task notification, not user input]
    Task:   Run full test suite
    Status: failed
    Output: <path of the task's output file>

  AI reads the output file:
    "47 passed, 3 failed
     FAIL: src/auth/login.test.ts
     FAIL: src/auth/session.test.ts
     FAIL: src/api/users.test.ts"

  AI: "The test suite found 3 failures. Let me fix them."

通知自然地出現在對話流程中。AI 不需要輪詢或檢查 — 當背景任務完成時它會自動被通知。如果 Claude 需要在命令仍在執行時就做出反應,例如面對新的 log 行或變動中的 CI 狀態,可以改用 Monitor 工具;它會在每一行新輸出出現時把它回傳給 Claude。

什麼適合在背景執行

不是每個命令都適合放在背景。以下是決策框架:

Need the result to decide your next action?
  ├── YES → Foreground (blocking)
  │   Examples:
  │   - "cat package.json" (need to read contents now)
  │   - "git status" (need to know state before committing)
  │   - "ls src/" (need to know what files exist)
  │
  └── NO → Background (non-blocking)
      Examples:
      - "npm test" (can write code while tests run)
      - "docker build ." (can prepare deployment config while building)
      - "pnpm build" (can write documentation while building)
操作耗時背景執行?原因
cat file.txt< 1s否立即需要結果
git diff< 1s否現在就需要看到變更
npm test10-120s是測試執行時可以繼續工作
docker build30-300s是長時間建構,不立即需要結果
npm install5-30s視情況取決於是否立即需要套件
pnpm build5-60s是可以同時準備部署設定
eslint .5-30s是可以在 linting 時繼續寫程式

交錯背景和前景工作

真正的威力在於將背景任務與有效的前景工作結合起來:

Timeline:
  ├── Launch: npm test (background)
  ├── Read: src/auth/login.ts (foreground, instant)
  ├── Read: src/auth/session.ts (foreground, instant)
  ├── Edit: fix suspected bug in login.ts (foreground)
  ├── [Notification: npm test completed, 3 failures]
  ├── Analyze: compare failures with the fix just made
  ├── Edit: fix remaining 2 test failures
  └── Launch: npm test (background, verify fixes)

AI 利用測試套件的執行時間做了有用的工作:它讀取了可能出錯的檔案,並在測試結果返回之前就開始修復最明顯的問題。

關鍵洞見

背景任務讓你避免閒置等待 — AI 可以在長時間操作執行時做有用的工作。 這不僅僅是一種優化;它從根本上改變了 AI 處理複雜任務的方式。

沒有背景執行的話,每個長時間操作都會在對話中創造一個空白區。AI 啟動一個建構,閒等 60 秒什麼都不做,然後繼續。這 60 秒本可以用來閱讀文件、撰寫程式碼或規劃下一步。

洞見更深層:背景任務改變了 AI 的規劃策略。當 AI 知道它可以在背景執行測試時,它更願意提早啟動測試(以獲得快速回饋),而不是等到它認為一切都完美了才執行。這導致更迭代、更回饋驅動的工作流程 — 更接近經驗豐富的開發者實際的工作方式。

把它想像成做菜。好的廚師不會站在烤箱前面看烤肉。他們開始烤,然後切蔬菜、準備醬汁、擺餐桌。烤箱會在完成時通知他們。背景任務給了 AI 同樣的交錯操作能力。

實作範例

邊測試邊寫程式

以下是一個利用背景任務的實際工作流程:

User: "Fix the failing tests in the auth module"

AI Plan:
  1. Run test suite in background to identify failures
  2. While tests run, read the auth module source code
  3. When test results arrive, cross-reference with source
  4. Fix each failure
  5. Re-run tests in background to verify

Execution:

Step 1: Launch tests in background
  → Bash(command="npm test -- --reporter json", run_in_background=true)
  → task ID and output file path returned immediately

Step 2: Read source files (while tests run)
  → Read("src/auth/middleware.ts")
  → Read("src/auth/routes.ts")
  → Read("src/auth/session.ts")
  → (AI now understands the auth module's structure)

Step 3: Test results arrive
  → Task notification: status failed
  → Read(<output file>): 3 tests failed
     - login.test.ts: "Expected 200, got 401"
     - session.test.ts: "Token expired error"
     - users.test.ts: "Missing required field"

Step 4: Fix with full context
  → AI already read the source files, can immediately
     correlate failures with code
  → Edit middleware.ts: fix token validation
  → Edit routes.ts: add missing field

Step 5: Verify in background
  → Bash(command="npm test", run_in_background=true)
  → Continue documenting the changes while tests run

背景命令的時間上限

Claude 可以為背景命令傳入 timeout(單位為毫秒):

{
  "type": "tool_use",
  "name": "Bash",
  "input": {
    "command": "npm run e2e-test",
    "description": "Run end-to-end test suite",
    "run_in_background": true,
    "timeout": 300000
  }
}

這個上限是否生效,取決於 session 在哪裡執行(Claude Code 2.1.288 及之後版本):

  • 你正在操作的本機 session(終端機、桌面 app、VS Code extension):背景命令沒有時間上限,會一直執行到結束,或直到你停止它,例如從 /tasks 停止。
  • 無人值守的 session(-p 執行、Agent SDK 應用程式、CI job、雲端 session):背景命令預設可執行 30 分鐘,或 Claude 隨 run_in_background 傳入的 timeout,最長 2 小時。以文字 prompt 啟動的 -p 執行則預設為 10 分鐘。
  • 達到上限時,Claude Code 會停止命令並告知 Claude;如果工作仍需要,Claude 可以用更長的 timeout 重新啟動它。

你不需要自己設定 timeout,由 Claude 在每次呼叫時決定。BASH_DEFAULT_TIMEOUT_MS 與 BASH_MAX_TIMEOUT_MS 環境變數可以提高這些上限,但不能縮短。背景時間上限在 Claude Code 2.1.285 加入,直到 2.1.288 之前適用於所有 session。

應避免的反模式

Bad: Running a quick command in background
  → Bash(command="cat README.md", run_in_background=true)
  → A task ID, an output file, and a later notification are
    pure overhead for a <1s operation

Bad: Launching many background tasks that compete for resources
  → 5 parallel "npm test" runs will slow each other down
  → Better: one background test run + foreground analysis

Bad: Launching a background task then immediately waiting for it
  → Bash(command="npm test", run_in_background=true)
  → Bash(command="sleep 30")  ← defeats the purpose!
  → Instead: do useful work, let the notification come naturally

Bad: Expecting a foreground subagent's background command to outlive it
  → the command stops when that subagent's run ends
  → Better: start long-lived work from the main conversation

不只是命令:背景 Subagents 與 Sessions

Claude Code 的背景執行分成三層:

層級如何開始在哪裡管理
背景命令Claude 設定 run_in_background、你按下 Ctrl+B,或前景命令達到逾時session 內的 /tasks
背景 subagentClaude 從主對話產生的 subagent 預設就在背景執行(Claude Code 2.1.232 及之後版本)agent panel 與 /tasks;它的權限提示會出現在你的 session
背景 session/background(別名 /bg)、claude --bg "<prompt>",或用 /fork 送出一份副本,同時繼續目前的工作claude agents(agent view,研究預覽功能)

背景 session 是完整的 Claude Code 對話,不需要連著終端機也會持續執行。把目前所在的 session 移到背景時,正在執行的背景命令、背景 subagents 與 /loop 任務都會一起移過去並繼續執行;無法搬移的執行中 Monitor 監看則會被停止。在 shell 中:

claude --bg "run the full test suite and fix any failures"
claude agents          # agent view: every background session
claude attach <id>     # open the session in this terminal
claude logs <id>       # print its recent output
claude stop <id>       # stop it; the conversation is kept
claude rm <id>         # delete it, and its worktree when that is safe

claude --bg 會印出這些命令所需的短 ID。以 claude --bg 或從 agent view 啟動的 session,在編輯檔案前會先移到自己的 git worktree;而 claude rm 會保留仍有未 commit 變更或未 push commits 的 worktree。第 12 堂課會說明這些 worktree 規則。

前後對比

僅前景執行有背景任務
AI 在長時間操作時閒置AI 在等待時持續有效工作
一次一個操作交錯前景和背景工作
測試只在「準備好」時才執行測試提早執行以獲得快速回饋
循序工作流程重疊的執行階段
90 秒測試 = 90 秒什麼都不做90 秒測試 = 90 秒有效寫程式
建構後部署要等兩次建構在背景執行,同時準備部署設定
每個長時間工作佔用一個終端機可從 shell 連上、查看與停止的背景 sessions

下一堂課

第 9 堂課介紹 Agent Teams 與通訊 — 一個 lead session 如何透過共享任務清單與直接訊息,協調多位各自擁有獨立上下文視窗的 Claude Code teammates,處理單一代理無法應付的問題。