MCPcopy Create free account
hub / github.com/cedriking/spark / TaskQueue

Class TaskQueue

src/task-queue.ts:3–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1type Task<T = void> = () => Promise<T>;
2
3export default class TaskQueue {
4 private tasks: Task[] = [];
5 private running: Promise<void> | undefined;
6 private intervals: NodeJS.Timer[] = [];
7
8 get length() {
9 return this.tasks.length;
10 }
11
12 run<T>(task: Task<T>): Promise<T> {
13 return new Promise((resolve, reject) => {
14 this.tasks.push(() => task().then(resolve).catch(reject));
15 this.runNext();
16 });
17 }
18
19 runPeriodically(task: Task, milliseconds: number): void {
20 let pending = false;
21 this.intervals.push(
22 setInterval(() => {
23 if (pending) return;
24 pending = true;
25 this.run(task).finally(() => {
26 pending = false;
27 });
28 }, milliseconds)
29 );
30 }
31
32 async stop() {
33 this.tasks.length = 0;
34 this.intervals.forEach(clearInterval);
35 this.intervals = [];
36 if (this.running) {
37 await this.running;
38 }
39 }
40
41 private async runNext() {
42 if (this.running) return;
43
44 const task = this.tasks.shift();
45 if (!task) return;
46
47 try {
48 await (this.running = task());
49 } finally {
50 this.running = undefined;
51 }
52
53 this.runNext();
54 }
55}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected