14.2 后台任务调度
后台任务不是「想跑就跑」:导入大资产时,缩略图生成、索引重建这种低优先级的活应该让路。本节的 TaskScheduler 给后台任务三件套:
submit(task):按优先级降序入队——高优先级的先执行。drain():按并发上限分批执行——同时最多 N 个任务在跑。cancel(id):取消某任务——已提交未执行的直接跳过。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 拉取队列 | 11.2 后台生成队列 | 缩略图是拉取(谁取谁跑);本节的调度器加优先级与并发 |
| 异步导入 | 14.1 异步导入任务 | 导入任务图定顺序,调度器定「几个并发、谁先跑」 |
| 派生缓存 | 8.2 派生资产与缓存失效 | 后台任务的产物进缓存,避免重复算 |
| 缩略图缓存 | 11.1 缩略图生成与缓存 | 缩略图是最典型的可取消后台任务 |
优先级:让低优先级的让路
任务队列最怕「低优先级的活霸占 CPU」。三个原则:
- 按优先级排:高优先级先执行。用户点了「导入」→ 高优先级;缩略图重生成 → 低优先级。
- 限并发:
concurrency是「同时几个」。多核并行是好事,但无限并发会把编辑器拖垮——IO 队列深度、内存压力都在涨。默认 2,导入高峰再降。 - 能取消:用户取消导入 / 资产被删除 →
cancel让没跑的任务跳过。取消只对「未执行」有效——正在跑的任务让它在下一次检查点自己停(协作式取消)。
对比 11.2 的拉取队列:那里队列不排优先级、不控并发(worker 自己取);这里是调度器管一切——优先级、并发、取消。两个都是「队列」,职责不同:拉取队列适合「低频、可控」的后台活,调度器适合「高频、竞争资源」的活。
对标任务依赖与调度
Unreal Tasks System 支持前置依赖和优先级。helio 本节在本地队列中控制等待任务的顺序、并发数量和取消,依赖约束由上一节的任务图提供。取消等待项和中断已经执行的任务需要分别定义。 Unreal Tasks System
可运行产物:6 条用例
下面 src/task-scheduler.ts 层级 L1,完整可编译,命令 node --test test/14-2-task-scheduler.test.ts:
// file: src/task-scheduler.ts
// tier: L1
// verify: node --test test/14-2-task-scheduler.test.ts
//
// 资产管线(第十四章):大资产与流式——后台任务调度。
// 编辑器的后台任务要排优先级、限并发、能取消。TaskScheduler 三件套:
// submit 按优先级降序入队,drain 按并发上限分批执行,cancel 让任务跳过
// 执行。缩略图(11.2)是拉取队列,这里补上优先级与并发——大资产导入
// 高峰时低优先级任务自动让路。
export interface Task {
id: string;
priority: number;
run: () => Promise<void>;
}
export class TaskScheduler {
readonly #queue: Task[] = [];
readonly #canceled = new Set<string>();
#concurrency: number;
#running = 0;
constructor(concurrency = 2) {
this.#concurrency = concurrency;
}
/** 提交任务;按优先级降序插入。 */
submit(task: Task): void {
this.#queue.push(task);
this.#queue.sort((a, b) => b.priority - a.priority);
}
cancel(id: string): void {
this.#canceled.add(id);
}
get pending(): number {
return this.#queue.length + this.#running;
}
/** 跑完队列里所有任务(按并发上限分批)。 */
async drain(): Promise<void> {
while (this.#queue.length > 0) {
const batch = this.#queue.splice(0, this.#concurrency);
await Promise.all(
batch.map(async (t) => {
if (this.#canceled.has(t.id)) return;
this.#running++;
try {
await t.run();
} finally {
this.#running--;
}
}),
);
}
}
}
submit 每次入队后 sort 按优先级降序——插入时排序保证 drain 取队首即最高优先级。drain 的 splice(0, concurrency) 按批取;每批 Promise.all 并行跑批内任务,批与批串行——同时最多 concurrency 个。cancel 在批内执行前检查——取消是「跳过」不是「中断在跑」。
可运行产物:6 条用例
下面是 test/14-2-task-scheduler.test.ts 层级 L1,命令 node --test test/14-2-task-scheduler.test.ts:
// file: test/14-2-task-scheduler.test.ts
// tier: L1
// verify: node --test test/14-2-task-scheduler.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TaskScheduler } from '../src/task-scheduler.ts';
test('高优先级先执行', async () => {
const order: string[] = [];
const s = new TaskScheduler(1);
s.submit({ id: 'low', priority: 0, run: async () => order.push('low') });
s.submit({ id: 'high', priority: 10, run: async () => order.push('high') });
await s.drain();
assert.deepEqual(order, ['high', 'low']);
});
test('并发上限:同时最多 N 个', async () => {
let active = 0;
let maxActive = 0;
const s = new TaskScheduler(2);
for (let i = 0; i < 4; i++) {
s.submit({
id: `t${i}`,
priority: 0,
run: async () => {
active++;
maxActive = Math.max(maxActive, active);
await new Promise((r) => setTimeout(r, 10));
active--;
},
});
}
await s.drain();
assert.ok(maxActive <= 2);
});
test('取消的任务不执行', async () => {
const order: string[] = [];
const s = new TaskScheduler(1);
s.submit({ id: 'a', priority: 0, run: async () => order.push('a') });
s.submit({ id: 'b', priority: 0, run: async () => order.push('b') });
s.cancel('a');
await s.drain();
assert.deepEqual(order, ['b']);
});
test('drain 执行全部任务', async () => {
const order: string[] = [];
const s = new TaskScheduler(3);
for (let i = 0; i < 5; i++) {
s.submit({ id: `t${i}`, priority: i, run: async () => order.push(`t${i}`) });
}
await s.drain();
assert.equal(order.length, 5);
});
test('pending 计数含队列与在跑', async () => {
const s = new TaskScheduler(1);
s.submit({ id: 'a', priority: 0, run: async () => new Promise((r) => setTimeout(r, 5)) });
s.submit({ id: 'b', priority: 0, run: async () => {} });
assert.equal(s.pending, 2);
await s.drain();
assert.equal(s.pending, 0);
});
test('空队列 drain 无异常', async () => {
const s = new TaskScheduler(2);
await s.drain();
assert.equal(s.pending, 0);
});
本机实测(Node v26.5.0,node --test test/14-2-task-scheduler.test.ts):tests 6、pass 6、fail 0,耗时约 50 ms。
第一条钉「优先级」——后提交的高优先级任务先跑(order = ['high','low']);第二条钉「并发上限」——4 个任务并发 2,maxActive ≤ 2;第三条钉「取消」——cancel('a') 后只有 b 执行。
小结
- 后台任务三件套:优先级入队、并发分批、可取消。
- 低优先级的活让路——导入高峰缩略图生成自动排队。
- 取消是「跳过未执行」,正在跑的协作式自停。
- 优先级归调度器、依赖归任务图(14.1),各管一段。
- 下一节让「大资产」真正能进内存:流式区块——分块 + LRU 缓存。
阅读导航:上一节:14.1 异步导入任务 · 下一节:14.3 流式区块 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。