Lesson 08

Background Tasks 后台任务

发射即忘 -- Agent 不会因为命令还在跑就卡住

// Fire-and-Forget Architecture 发射即忘架构

MAIN THREAD Agent Loop 主线程 1. User: "Run tests & lint" 用户请求同时运行测试和lint 2. spawn_background( "npm test", "npm run lint") 发射即忘 fire-and-forget 3. Agent continues working Agent 继续做其他事情,不等待 4. Edit code, read files... 编辑代码、读取文件... 5. drain_notifications() Before next LLM call 每次 LLM 调用前清空通知队列 6. LLM call (with results) Results injected as context 结果作为上下文注入 LLM 调用 7. "Tests pass, 2 lint warns" 综合后台结果回复用户 BACKGROUND Parallel Execution 并行执行 npm test Running 42 test suites... ✓ Complete (exit 0) Duration: 12.3s npm run lint Checking 128 files... ⚠ 2 warnings (exit 0) Duration: 8.1s Notification Queue 通知队列 ✓ npm test: PASSED ⚠ npm lint: 2 warnings Timeline View 时间线视图 t0: spawn tasks Agent 发射后台任务 Agent works on other things 做其他事情 test 12.3s lint 8.1s t1: lint done Result queued t2: test done Result queued t3: drain_notifications 清空队列,注入结果 t4: LLM call With all results attached 附带所有结果 t5: response "Tests pass, 2 lint warns" Total time: max(12.3, 8.1) = 12.3s Push not Pull 推送而非拉取 Background tasks PUSH results to notification queue. Agent does NOT poll. push model = no wasted cycles
CONCEPT 01

不阻塞

长时间运行的命令(测试、构建、lint)放入后台执行。Agent 不会卡住等待,可以继续编辑代码、读取文件、做其他工作。

spawn → forget → keep working

CONCEPT 02

通知队列

后台任务完成后把结果推入通知队列(push model)。Agent 不需要轮询检查任务是否完成,结果会主动送达。

push, not poll = zero waste

CONCEPT 03

drain 机制

每次发起 LLM 调用之前,自动执行 drain_notifications() 清空队列。后台结果作为额外上下文注入到下一次 LLM 调用中。

drain → inject → LLM call

试一试 Try It Out

1

"在后台运行 'sleep 5 && echo done',然后创建一个文件"

"Run 'sleep 5 && echo done' in the background, then create a file while it runs"

2

"启动 3 个后台任务:'sleep 2'、'sleep 4'、'sleep 6'。检查它们的状态。"

"Start 3 background tasks: 'sleep 2', 'sleep 4', 'sleep 6'. Check their status."

3

"在后台运行 mvn test,同时做其他事情"

"Run mvn test in the background and keep working on other things"