multi-tasks 3.5.2 → 4.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,319 +1,324 @@
1
- # multi-tasks
2
-
3
- Run large batches of tasks in parallel across multiple Node.js processes, with zero dependencies. Progress and results are stored on the file system, so an interrupted run (crash, power outage) can resume where it left off.
4
-
5
- **New in 3.5.0 — `task_storage: 'memory'`**: keep all task state in the master process's memory instead of on disk. Same API, one config field and ~17× faster on huge batches of small tasks. The trade-off: no resume. See [Task storage modes](#task-storage-modes).
6
-
7
- ![task_storage benchmark: file mode 195.1s vs memory mode 11.2s17.4x faster](https://cdn.jsdelivr.net/npm/multi-tasks@latest/bench-storage.svg)
8
-
9
- ### Install:
10
-
11
- ```text
12
- npm install multi-tasks
13
- ```
14
-
15
- ### Quick start:
16
-
17
- ```javascript
18
- let multiTasks = require('multi-tasks').multiTasks;
19
-
20
- //your tasks, as a plain array
21
- let tasks = [];
22
- for(let i = 0; i < 50; i++){
23
- tasks.push({name: `task-${i}`});
24
- };
25
-
26
- multiTasks({
27
- initialTasks: tasks,
28
- //process one task and return its result (a plain value or a Promise)
29
- processTask: (task, helper) => {
30
- return `done: ${task.name}`;
31
- },
32
- taskRootFolder: './my-tasks', //progress and results live in ./my-tasks/demo
33
- taskId: 'demo',
34
- numberOfWorkers: 3, //worker processes running in parallel
35
- autoCloseAfterCompletion: true, //exit the process when all tasks are done
36
- onFinish: (report) => {
37
- console.log(`${report.succeeded} succeeded, ${report.failed} failed`);
38
- },
39
- });
40
- ```
41
-
42
- Results are written as JSON files under `<taskRootFolder>/<taskId>/results/succ`, failures under `results/errors`. While running, a live progress bar shows in the terminal to watch the run from a browser, see [Real-Time Monitoring](#real-time-monitoring). A runnable copy of this example lives in `examples/example0`.
43
-
44
- ### Results and errors:
45
-
46
- `processTask` may return a plain value or a Promise:
47
-
48
- ```javascript
49
- let processTask = (task, helper) => {
50
- let {taskCount} = task; //0-based index of this task
51
-
52
- return new Promise((resolve, reject) => {
53
- setTimeout(() => {
54
- resolve({data: `task${taskCount} complete`});
55
- }, 100);
56
- });
57
- };
58
- ```
59
-
60
- A failing task never stops the batch — its error is captured and saved to `results/errors`, the rest keep going:
61
-
62
- ```javascript
63
- let processTask = (task, helper) => {
64
- let {taskCount} = task;
65
-
66
- if(taskCount === 3) throw 'exception'; //a thrown value is persisted as-is
67
- if(taskCount === 4) return Promise.reject({err: 'a test error'}); //a rejection value is persisted as-is
68
- if(taskCount === 5) aaa = bbb; //a ReferenceError is captured too
69
-
70
- return {data: 'succ'};
71
- };
72
- ```
73
-
74
- ### Creating new tasks dynamically:
75
-
76
- ```javascript
77
- //scenario: crawl a paginated API — each page tells you if there is a next one
78
- let processTask = async (task, helper) => {
79
- let page = await fetchPage(task.url); //your logic here
80
-
81
- if(page.nextUrl){
82
- //a discovered next page becomes a new task;
83
- //the pages are finite, so the queue always drains on its own
84
- helper.createNewTasks({url: page.nextUrl});
85
- };
86
-
87
- return {url: task.url, items: page.items};
88
- };
89
-
90
- multiTasks({
91
- initialTasks: [{url: 'https://api.example.com/items?page=1'}], //start from the first page
92
- processTask,
93
- taskRootFolder: './my-tasks',
94
- taskId: 'api-crawl',
95
- numberOfWorkers: 3,
96
- //keep autoCloseAfterCompletion false (the default) while tasks may still be created
97
- });
98
- ```
99
-
100
- The point: new tasks come from work discovered while processing, and discovery stops when the data runs out — no artificial bound needed. Keep `autoCloseAfterCompletion` at its default (`false`) so workers stay alive for late-arriving tasks.
101
-
102
- ### Timeouts and retries:
103
-
104
- ```javascript
105
- multiTasks({
106
- initialTasks: tasks,
107
- processTask,
108
- taskRootFolder: './my-tasks',
109
- taskId: 'demo',
110
- numberOfWorkers: 3,
111
- taskTimeout: 30000, //a task that overruns 30s fails with a timeout error
112
- maxTaskRetries: 2, //auto-retry a failed task (worker crash, processTask error, or timeout) up to 2 times
113
- });
114
- ```
115
-
116
- ### Resuming an interrupted run:
117
-
118
- Just re-run the same code — `multiTasks(config)` detects the existing task folder and auto-resumes, re-running only the stuck tasks:
119
-
120
- ```javascript
121
- multiTasks(config); //same command, same config as the interrupted run
122
- ```
123
-
124
- Or point `initialTasks` at the task folder — same effect:
125
-
126
- ```javascript
127
- multiTasks({...config, initialTasks: '/myworks/my_scan_tasks/my-task'});
128
- ```
129
-
130
- Or resume from the task folder alone — the config (including `processTask`) is restored from `task_config.json`:
131
-
132
- ```javascript
133
- multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task'}); //taskFolder: the full path of the existing task folder
134
- ```
135
-
136
- **Note:** functions revived from `task_config.json` must be **self-contained** (no outer-scope variables; `require(...)` inside the body) — otherwise pass them again; fields you pass always win:
137
-
138
- ```javascript
139
- multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task', processTask});
140
- ```
141
-
142
- Note: a folder created with `task_storage: 'memory'` holds no recoverable state — resuming it throws.
143
-
144
- ### Retrying failed tasks:
145
-
146
- Resume an interrupted run and also re-run the tasks that failed (in `progress/finished_with_errors`):
147
-
148
- ```javascript
149
- multiTasks.retry_fails({taskFolder: '/myworks/my_scan_tasks/my-task'});
150
- ```
151
-
152
- ### Restarting from scratch:
153
-
154
- Throw away all progress and results in a task folder and re-run all the initial tasks (the config, including `processTask` and `initialTasks`, is restored from `task_config.json`):
155
-
156
- ```javascript
157
- multiTasks.restart({taskFolder: '/myworks/my_scan_tasks/my-task'});
158
- ```
159
-
160
- Unlike `retry_fails` (which re-runs only the failed tasks), `restart` re-runs **all the initial tasks** — tasks created dynamically via `helper.createNewTasks` are not restored and will not be re-run. Fields you pass override the saved config and are written back into it; the same self-contained-function note as in Resuming applies.
161
-
162
- ### Task storage modes:
163
-
164
- By default every task state change is written to disk immediately (`file` mode), which is what makes resume/retry/restart possible. For very large or very fast batches you can trade durability for speed:
165
-
166
- ```javascript
167
- multiTasks({
168
- initialTasks: tasks,
169
- processTask,
170
- taskRootFolder: './my-tasks',
171
- taskId: 'demo',
172
- task_storage: 'memory', //'file' (default) | 'memory'
173
- onFinish: (report, helper) => {
174
- helper.foreachResult((count, task, result, succeeded) => {
175
- //collect / batch-insert / write out your results here
176
- });
177
- },
178
- });
179
- ```
180
-
181
- - **`file`** (default) every state change hits disk immediately; resume anytime.
182
- - **`memory`** — task states, results and logs stay in the master's memory; nothing per-task is written to disk, so `onFinish(report, helper)` is the only exit for your results — collect them with `helper.foreachResult` (or `foreachSuccResult`/`foreachErrorResult`) as above; if you need per-task files, write them in bulk there. `resume`/`retry_fails`/`restart` throw — a killed run is simply gone.
183
-
184
- Benchmark — 30,000 tiny tasks × 28 workers:
185
-
186
- ![task_storage benchmark: file mode 195.1s vs memory mode 11.2s — 17.4x faster](https://cdn.jsdelivr.net/npm/multi-tasks@latest/bench-storage.svg)
187
-
188
- Caveats of `memory` mode:
189
-
190
- - **Monitoring**: [multi-tasks-monitor](#real-time-monitoring) reads the task folder, so it has nothing to show for a `memory` run.
191
- - **Worker crashes**: without `maxTaskRetries`, a crashed worker's in-flight task is lost for good (no `resume` to pick it up).
192
- - **Dynamic tasks**: tasks sent via `helper.createNewTasks` but not yet applied are lost if the master is killed. And keep `autoCloseAfterCompletion` at its default `false` when workers create tasks dynamically — in-transit tasks can miss the dispatch window and the workers get closed early.
193
-
194
- ### Broadcasting events between workers:
195
-
196
- ```javascript
197
- multiTasks({
198
- initialTasks: tasks,
199
- processTask: (task, helper) => {
200
- helper.setListener('task-done', (payload, meta) => {
201
- console.log(`worker ${meta.fromWorkerPid} says: task ${payload.seq} done`);
202
- });
203
- helper.emit('task-done', {seq: task.seq}); //broadcast to all workers
204
- return {data: 'succ'};
205
- },
206
- taskRootFolder: './my-tasks',
207
- taskId: 'demo',
208
- numberOfWorkers: 3,
209
- });
210
- ```
211
-
212
- ### System events:
213
-
214
- Send events from a worker to the master with `helper.emitSys`:
215
-
216
- ```javascript
217
- multiTasks({
218
- initialTasks: tasks,
219
- setSysListener: (event, payload, meta) => {
220
- console.log(`sys event "${event}" from worker ${meta.fromWorkerPid}:`, payload);
221
- },
222
- processTask: (task, helper) => {
223
- helper.emitSys('task-started', {seq: task.seq});
224
- if(task.fatal){
225
- helper.emitSys('TERMINATE_ALL_WORKERS'); //built-in event: stop everything
226
- return;
227
- };
228
- return {data: 'succ'};
229
- },
230
- taskRootFolder: './my-tasks',
231
- taskId: 'demo',
232
- numberOfWorkers: 3,
233
- });
234
- ```
235
-
236
- ### Real-Time Monitoring
237
-
238
- Monitor your running tasks with [multi-tasks-monitor](https://www.npmjs.com/package/multi-tasks-monitor) — see its npm page for full details.
239
-
240
- Quick start (requires multi-tasks >=3.2.0): once your multi-tasks run has started, the startup log prints the monitor command with the task folder path already filled in — just copy-paste it into another terminal:
241
-
242
- ```text
243
- npm install multi-tasks-monitor
244
- npx multi-tasks-monitor --task-dir "D:\tasks\multitasks20260806..." --port 3777
245
- ```
246
-
247
- ### API:
248
-
249
- **Entry functions:**
250
-
251
- - **`multiTasks(config)`** — run tasks; auto-resumes if the task folder already exists or `initialTasks` points to one.
252
- - **`multiTasks.resume(config)`** — resume from the task folder alone (`{taskFolder}`); the config is restored from `task_config.json`, fields you pass override it and are written back. Usually you don't need this: re-running `multiTasks(config)` auto-resumes.
253
- - **`multiTasks.retry_fails(config)`** — same as `resume`, and also retries the failed tasks.
254
- - **`multiTasks.restart(config)`** — wipe the task folder's progress and results and re-run from scratch (`{taskFolder}`). **All previous progress and results are deleted.**
255
-
256
- **Config options:**
257
-
258
- - **`initialTasks`** — an array of task objects; a function returning the array (or a Promise of it); or a task folder path string to resume from.
259
- - Function form, for performance: every worker process re-runs your entire entry script, so top-level task-generation code (scanning folders, querying a database, ...) runs once per worker. Wrapped in a function it is called **only once, in the master process**, and workers never call it. The (resolved) value must be an array, otherwise the master exits with an error. The resulting array — not the function — is stored in `task_config.json`, so the self-contained-function note under Resuming does not apply to it.
260
- - **`processTask(task, helper)`** — required; return a result or a Promise with result. Results are stored as JSON in `results/succ/<subid>.json`; if a result is not JSON-serializable, the task still counts as succeeded (a placeholder is stored) and a warning shows up in the command line and in monitor tools.
261
- - **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
262
- - **`taskId`** — task folder name under `taskRootFolder`.
263
- - **`numberOfWorkers`** how many worker processes run in parallel; a number, or a percentage string of CPU cores like `"50%"` (default).
264
- - **`taskTimeout`** — optional, milliseconds; an overdue task fails with a timeout error.
265
- - **`maxTaskRetries`** — optional, max times a failed task is auto-retried.
266
- - **`workerPriority`** — optional, OS scheduling priority for worker processes: `'low' | 'below_normal' | 'normal' | 'above_normal' | 'high'`, or a nice number (integer -20~19). Lower priority keeps the machine responsive while a long batch occupies all cores; invalid values throw before any task folder is created.
267
- - **`progressBar`** — `true` by default: shows a live progress bar in the terminal; set `false` to fall back to plain log output.
268
- - **`worker_status_poll_ms`** — worker status poll interval in ms; default `2000`; `0` (or `false`) disables the worker status table; `true` means the default rate.
269
- - **`task_storage`** — `'file'` (default) | `'memory'`: where task states and results are kept; see "Task storage modes".
270
- - **`autoCloseAfterCompletion`** — set `true` to kill workers and exit the process when no tasks are left; default is `false`, i.e. workers stay alive waiting for dynamically created tasks.
271
- - **`shouldTerminate(info)`** — return `true` to terminate the whole process. If it throws, the error is logged and the task is dispatched anyway (treated as "don't terminate").
272
- - **`setSysListener(event, payload, meta)`** — optional, handle custom system events (sent via `helper.emitSys`) on the master; `meta` has `fromWorkerId` and `fromWorkerPid`.
273
- - **`onFinish(report, helper)`** — called once after all workers exit (only when `autoCloseAfterCompletion` is `true`). `report` summarizes the run: `{ taskId, taskFolder, startTimestamp, endTimestamp, cost, total, succeeded, failed, failedTasks, succButSaveFailed, workers }` `cost` is the run duration in ms (a resumed run measures only the current round); `failedTasks` lists the failed tasks' subids; `succButSaveFailed` counts tasks that ran fine but whose results could not be JSON-serialized (details in `<taskFolder>/.sys/user_messages/`); `workers` is `{ count, crashed }` — the configured worker count and how many workers crashed and were replaced. `helper` walks every persisted task result:
274
- - **`helper.foreachSuccResult((count, task, result) => {})`** — iterate all succeeded results (`results/succ`); `count` is a 0-based index, `task` is the original task object (`null` if its task file is missing or unparseable), `result` is the value returned by `processTask` (`undefined` when the task returned nothing; a `{type: 'result_serialize_error', message}` placeholder when the value could not be JSON-serialized).
275
- - **`helper.foreachErrorResult((count, task, err) => {})`** — iterate all failed results (`results/errors`); `err` is the persisted error object as-is (`{ex}` / `{subTask, exception}` / `{type: 'timeout', ...}` / `{type: 'worker_crash', ...}`). A non-`Error` rejection value that is not JSON-serializable is persisted as `{ex: {type: 'unserializable_error_value', ...}}`.
276
- - **`helper.foreachResult((count, task, result, succeeded) => {})`** — iterate all results regardless of outcome (succeeded first, then failed; `count` runs continuously across both); `succeeded` is `true` for results from `results/succ` and `false` for those from `results/errors` (where `result` is the persisted error object).
277
- - Iteration follows filesystem order (not sorted). `onFinish` runs synchronously at the very end and the master process exits shortly after it returnsdon't `await` inside it. In `memory` mode the helpers iterate the in-memory results the same way (in completion order).
278
-
279
- **Other options:**
280
-
281
- - **`taskFolder`** full task folder path; only used by `resume`/`retry_fails`/`restart`.
282
-
283
- **Task helper** (the `helper` object passed as the second argument of `processTask`):
284
-
285
- - **`helper.createNewTasks(tasks)`** — create new tasks dynamically while processing.
286
- - **`helper.emit(event, payload, option?)`** — broadcast an event to all workers (relayed by the master, best-effort); `option.includingMe` defaults to `true` — pass `{includingMe: false}` to exclude the sender. Payload must be JSON-serializable.
287
- - **`helper.setListener(event, handler)`** listen for broadcast events; one handler per event per worker process (re-registering replaces it), so calling it inside `processTask` is always safe; `handler(payload, meta)` gets `meta.fromWorkerId` and `meta.fromWorkerPid`. Broadcasts are runtime-only messages — not persisted, not replayed on resume.
288
- - **`helper.emitSys(event, payload?)`** — send a system event to the master (consumed by the master itself, not relayed). Built-in event: `'TERMINATE_ALL_WORKERS'` force-kills all workers and exits the master; any other event goes to `config.setSysListener`.
289
-
290
- ### Changelog:
291
-
292
- - 3.5.2 Fix Readme
293
- - 3.5.1 Fix bench-storage.svg
294
- - 3.5.0 Add `task_storage: 'memory'` mode (~17x faster, no resume)
295
- - 3.4.1 Rewrite README: simpler structure, all examples verified by test cases
296
- - 3.4.0 Show per-worker load (ELU/CPU/memory) under progressBar; stability fixes
297
- - 3.3.0 Unserializable results still succeed; shouldTerminate throwing is safe; progressBar counters added
298
- - 3.2.3 Support workerPriority: set OS scheduling priority for worker processes
299
- - 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
300
- - 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
301
- - 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
302
- - 3.1.9 Print the multi-tasks-monitor command on startup
303
- - 3.1.8 Small refinements
304
- - 3.1.7 onFinish: iterate all succ/failed results via helper.foreachSuccResult/foreachErrorResult
305
- - 3.1.6 Fix silent task loss under heavy load with maxTaskRetries
306
- - 3.1.4 Rewrite methods multiTasks.resume/retry_fails/restart
307
- - 3.1.0 Support worker broadcast and system events; default numberOfWorkers is now "50%" of CPU cores
308
- - 3.0.3 Support 'maxTaskRetries'
309
- - 3.0.2 Support 'taskTimeout'
310
- - 3.0.1 Versions 3.0.0 and above are maintained by AI
311
- - 3.0.0 and earlier: see the git history
312
-
313
- ### Gitee:
314
-
315
- [https://gitee.com/zhanglei923/multi-tasks](https://gitee.com/zhanglei923/multi-tasks)
316
-
317
- ### License:
318
-
319
- [MIT](https://opensource.org/license/MIT)
1
+ # multi-tasks
2
+
3
+ Run large batches of tasks in parallel across multiple Node.js processes, with zero dependencies. Progress and results are stored on the file system, so an interrupted run (crash, power outage) can resume where it left off.
4
+
5
+ **New in 4.0.0 — `task_storage: 'aof'` (append-only file), now the default**: `memory`-grade speed **with** full resume a killed run simply continues where it left off. One config field; set `task_storage: 'file'` for the classic per-task-file layout. See [Task storage modes](#task-storage-modes).
6
+
7
+ ![task_storage benchmark (100k tasks): file 439s vs aof 8.7s vs memory 7.3saof ≈ memory, 50x faster than file](https://cdn.jsdelivr.net/npm/multi-tasks@latest/bench-storage.svg)
8
+
9
+ ### Install:
10
+
11
+ ```text
12
+ npm install multi-tasks
13
+ ```
14
+
15
+ ### Quick start:
16
+
17
+ ```javascript
18
+ let multiTasks = require('multi-tasks').multiTasks;
19
+
20
+ //your tasks, as a plain array
21
+ let tasks = [];
22
+ for(let i = 0; i < 50; i++){
23
+ tasks.push({name: `task-${i}`});
24
+ };
25
+
26
+ multiTasks({
27
+ initialTasks: tasks,
28
+ //process one task and return its result (a plain value or a Promise)
29
+ processTask: (task, helper) => {
30
+ return `done: ${task.name}`;
31
+ },
32
+ taskRootFolder: './my-tasks', //progress and results live in ./my-tasks/demo
33
+ taskId: 'demo',
34
+ numberOfWorkers: 3, //worker processes running in parallel
35
+ autoCloseAfterCompletion: true, //exit the process when all tasks are done
36
+ onFinish: (report) => {
37
+ console.log(`${report.succeeded} succeeded, ${report.failed} failed`);
38
+ },
39
+ });
40
+ ```
41
+
42
+ Results are appended to `<taskRootFolder>/<taskId>/results/succ.json`, failures to `results/errors.json` one JSON line per task (`{"subid": ..., "data": ...}`); other storage modes lay them out differently (see [Task storage modes](#task-storage-modes)). A runnable copy of this example lives in `examples/example0`.
43
+
44
+ ### Results and errors:
45
+
46
+ `processTask` may return a plain value or a Promise:
47
+
48
+ ```javascript
49
+ let processTask = (task, helper) => {
50
+ let {taskCount} = task; //0-based index of this task
51
+
52
+ return new Promise((resolve, reject) => {
53
+ setTimeout(() => {
54
+ resolve({data: `task${taskCount} complete`});
55
+ }, 100);
56
+ });
57
+ };
58
+ ```
59
+
60
+ A failing task never stops the batch — its error is captured and saved to `results/errors.json` (in `memory` mode it is kept in the master's memory and surfaced via `onFinish`), the rest keep going:
61
+
62
+ ```javascript
63
+ let processTask = (task, helper) => {
64
+ let {taskCount} = task;
65
+
66
+ if(taskCount === 3) throw 'exception'; //a thrown value is persisted as-is
67
+ if(taskCount === 4) return Promise.reject({err: 'a test error'}); //a rejection value is persisted as-is
68
+ if(taskCount === 5) aaa = bbb; //a ReferenceError is captured too
69
+
70
+ return {data: 'succ'};
71
+ };
72
+ ```
73
+
74
+ ### Creating new tasks dynamically:
75
+
76
+ ```javascript
77
+ //scenario: crawl a paginated API — each page tells you if there is a next one
78
+ let processTask = async (task, helper) => {
79
+ let page = await fetchPage(task.url); //your logic here
80
+
81
+ if(page.nextUrl){
82
+ //a discovered next page becomes a new task;
83
+ //the pages are finite, so the queue always drains on its own
84
+ helper.createNewTasks({url: page.nextUrl});
85
+ };
86
+
87
+ return {url: task.url, items: page.items};
88
+ };
89
+
90
+ multiTasks({
91
+ initialTasks: [{url: 'https://api.example.com/items?page=1'}], //start from the first page
92
+ processTask,
93
+ taskRootFolder: './my-tasks',
94
+ taskId: 'api-crawl',
95
+ numberOfWorkers: 3,
96
+ //keep autoCloseAfterCompletion false (the default) while tasks may still be created
97
+ });
98
+ ```
99
+
100
+ The point: new tasks come from work discovered while processing, and discovery stops when the data runs out — no artificial bound needed. Keep `autoCloseAfterCompletion` at its default (`false`) so workers stay alive for late-arriving tasks.
101
+
102
+ ### Timeouts and retries:
103
+
104
+ ```javascript
105
+ multiTasks({
106
+ initialTasks: tasks,
107
+ processTask,
108
+ taskRootFolder: './my-tasks',
109
+ taskId: 'demo',
110
+ numberOfWorkers: 3,
111
+ taskTimeout: 30000, //a task that overruns 30s fails with a timeout error
112
+ maxTaskRetries: 2, //auto-retry a failed task (worker crash, processTask error, or timeout) up to 2 times
113
+ });
114
+ ```
115
+
116
+ ### Resuming an interrupted run:
117
+
118
+ Just re-run the same code — `multiTasks(config)` detects the existing task folder and auto-resumes, re-running only the stuck tasks:
119
+
120
+ ```javascript
121
+ multiTasks(config); //same command, same config as the interrupted run
122
+ ```
123
+
124
+ Or point `initialTasks` at the task folder — same effect:
125
+
126
+ ```javascript
127
+ multiTasks({...config, initialTasks: '/myworks/my_scan_tasks/my-task'});
128
+ ```
129
+
130
+ Or resume from the task folder alone — the config (including `processTask`) is restored from `task_config.json`:
131
+
132
+ ```javascript
133
+ multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task'}); //taskFolder: the full path of the existing task folder
134
+ ```
135
+
136
+ **Note:** functions revived from `task_config.json` must be **self-contained** (no outer-scope variables; `require(...)` inside the body) — otherwise pass them again; fields you pass always win:
137
+
138
+ ```javascript
139
+ multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task', processTask});
140
+ ```
141
+
142
+ ### Retrying failed tasks:
143
+
144
+ Resume an interrupted run and also re-run the tasks that failed:
145
+
146
+ ```javascript
147
+ multiTasks.retry_fails({taskFolder: '/myworks/my_scan_tasks/my-task'});
148
+ ```
149
+
150
+ ### Restarting from scratch:
151
+
152
+ Throw away all progress and results in a task folder and re-run all the initial tasks (the config, including `processTask` and `initialTasks`, is restored from `task_config.json`):
153
+
154
+ ```javascript
155
+ multiTasks.restart({taskFolder: '/myworks/my_scan_tasks/my-task'});
156
+ ```
157
+
158
+ Unlike `retry_fails` (which re-runs only the failed tasks), `restart` re-runs **all the initial tasks** — tasks created dynamically via `helper.createNewTasks` are not restored and will not be re-run. Fields you pass override the saved config and are written back into it; the same self-contained-function note as in Resuming applies.
159
+
160
+ ### Task storage modes:
161
+
162
+ By default (`aof` mode) you get near-`memory` speed **with** full resume. The classic `file` mode (per-task files on disk, live-monitorable) is one config field away. The three modes side by side:
163
+
164
+ | Mode | Time (100k tiny tasks) | `resume` / `retry_fails` / `restart` | Results readable from disk | Live monitoring ([multi-tasks-monitor](#real-time-monitoring)) |
165
+ |---|---|---|---|---|
166
+ | **`file`** | 439s (~7 min) | ✓ | ✓ | ✓ |
167
+ | **`aof`** (default) | 8.7s | ✓ | ✓ | ✗ |
168
+ | **`memory`** | 7.3s | throw | ✗ | ✗ |
169
+
170
+ Same API for all three — one config field:
171
+
172
+ ```javascript
173
+ multiTasks({
174
+ initialTasks: tasks,
175
+ processTask,
176
+ taskRootFolder: './my-tasks',
177
+ taskId: 'demo',
178
+ task_storage: 'aof', //'aof' (default) | 'file' | 'memory'
179
+ onFinish: (report, helper) => {
180
+ helper.foreachResult((count, task, result, succeeded) => {
181
+ //collect / batch-insert / write out your results here
182
+ });
183
+ },
184
+ });
185
+ ```
186
+
187
+ Reading results: in `aof` mode results stream into `results/succ.json`/`results/errors.json` (one JSON line per task) as tasks complete — while the run is in progress the same task may appear on several lines and the last one wins; when the run finishes, each file is rewritten to exactly one line per task. In `memory` mode results never touch disk — collect them in `onFinish(report, helper)` with `helper.foreachResult` (or `foreachSuccResult`/`foreachErrorResult`).
188
+
189
+ Caveats of `memory` mode:
190
+
191
+ - **Worker crashes**: without `maxTaskRetries`, a crashed worker's in-flight task is lost for good (no `resume` to pick it up).
192
+ - **Dynamic tasks**: tasks sent via `helper.createNewTasks` but not yet applied are lost if the master is killed. And keep `autoCloseAfterCompletion` at its default `false` when workers create tasks dynamically — in-transit tasks can miss the dispatch window and the workers get closed early.
193
+
194
+ Caveats of `aof` mode:
195
+
196
+ - **Results**: result files can lag a moment behind completion during the run; a resumed run always ends with a complete set.
197
+
198
+ ### Broadcasting events between workers:
199
+
200
+ ```javascript
201
+ multiTasks({
202
+ initialTasks: tasks,
203
+ processTask: (task, helper) => {
204
+ helper.setListener('task-done', (payload, meta) => {
205
+ console.log(`worker ${meta.fromWorkerPid} says: task ${payload.seq} done`);
206
+ });
207
+ helper.emit('task-done', {seq: task.seq}); //broadcast to all workers
208
+ return {data: 'succ'};
209
+ },
210
+ taskRootFolder: './my-tasks',
211
+ taskId: 'demo',
212
+ numberOfWorkers: 3,
213
+ });
214
+ ```
215
+
216
+ ### System events:
217
+
218
+ Send events from a worker to the master with `helper.emitSys`:
219
+
220
+ ```javascript
221
+ multiTasks({
222
+ initialTasks: tasks,
223
+ setSysListener: (event, payload, meta) => {
224
+ console.log(`sys event "${event}" from worker ${meta.fromWorkerPid}:`, payload);
225
+ },
226
+ processTask: (task, helper) => {
227
+ helper.emitSys('task-started', {seq: task.seq});
228
+ if(task.fatal){
229
+ helper.emitSys('TERMINATE_ALL_WORKERS'); //built-in event: stop everything
230
+ return;
231
+ };
232
+ return {data: 'succ'};
233
+ },
234
+ taskRootFolder: './my-tasks',
235
+ taskId: 'demo',
236
+ numberOfWorkers: 3,
237
+ });
238
+ ```
239
+
240
+ ### Real-Time Monitoring
241
+
242
+ Monitor your running tasks with [multi-tasks-monitor](https://www.npmjs.com/package/multi-tasks-monitor) — see its npm page for full details.
243
+
244
+ Quick start (requires multi-tasks >=3.2.0 and `task_storage: 'file'` — `aof`/`memory` runs have nothing to monitor): once your multi-tasks run has started, the startup log prints the monitor command with the task folder path already filled in — just copy-paste it into another terminal:
245
+
246
+ ```text
247
+ npm install multi-tasks-monitor
248
+ npx multi-tasks-monitor --task-dir "D:\tasks\multitasks20260806..." --port 3777
249
+ ```
250
+
251
+ ### API:
252
+
253
+ **Entry functions:**
254
+
255
+ - **`multiTasks(config)`** — run tasks; auto-resumes if the task folder already exists or `initialTasks` points to one.
256
+ - **`multiTasks.resume(config)`** — resume from the task folder alone (`{taskFolder}`); the config is restored from `task_config.json`, fields you pass override it and are written back. Usually you don't need this: re-running `multiTasks(config)` auto-resumes.
257
+ - **`multiTasks.retry_fails(config)`** — same as `resume`, and also retries the failed tasks.
258
+ - **`multiTasks.restart(config)`** — wipe the task folder's progress and results and re-run from scratch (`{taskFolder}`). **All previous progress and results are deleted.**
259
+
260
+ **Config options:**
261
+
262
+ - **`initialTasks`** — an array of task objects; a function returning the array (or a Promise of it); or a task folder path string to resume from.
263
+ - Function form, for performance: every worker process re-runs your entire entry script, so top-level task-generation code (scanning folders, querying a database, ...) runs once per worker. Wrapped in a function it is called **only once, in the master process**, and workers never call it. The (resolved) value must be an array, otherwise the master exits with an error. Only the resulting array is saved — not the function — so the self-contained-function note under Resuming does not apply to it.
264
+ - **`processTask(task, helper)`** — required; return a result or a Promise with result. Results are appended as JSON lines to `results/succ.json` (in `file` mode stored as per-task JSON files under `results/succ`; in `memory` mode kept in the master's memory and iterated via `onFinish` helpers); if a result is not JSON-serializable, the task still counts as succeeded (a placeholder is stored) and a warning shows up in the command line.
265
+ - **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
266
+ - **`taskId`** — task folder name under `taskRootFolder`.
267
+ - **`numberOfWorkers`** — how many worker processes run in parallel; a number, or a percentage string of CPU cores like `"50%"` (default).
268
+ - **`taskTimeout`** — optional, milliseconds; an overdue task fails with a timeout error.
269
+ - **`maxTaskRetries`** — optional, max times a failed task is auto-retried.
270
+ - **`workerPriority`** — optional, OS scheduling priority for worker processes: `'low' | 'below_normal' | 'normal' | 'above_normal' | 'high'`, or a nice number (integer -20~19). Lower priority keeps the machine responsive while a long batch occupies all cores; invalid values throw.
271
+ - **`progressBar`** — `true` by default: shows a live progress bar in the terminal; set `false` to fall back to plain log output.
272
+ - **`worker_status_poll_ms`** — worker status poll interval in ms; default `2000`; `0` (or `false`) disables the worker status table; `true` means the default rate.
273
+ - **`task_storage`** — `'aof'` (default) | `'file'` | `'memory'`: where task states and results are kept; see "Task storage modes". Note: on `resume`/`retry_fails`/`restart` the folder's own mode always wins (an old folder is never re-interpreted under the new default), and passing a `task_storage` that contradicts it throws.
274
+ - **`autoCloseAfterCompletion`** — set `true` to kill workers and exit the process when no tasks are left; default is `false`, i.e. workers stay alive waiting for dynamically created tasks.
275
+ - **`shouldTerminate(info)`** — return `true` to terminate the whole process. If it throws, the error is logged and the task is dispatched anyway (treated as "don't terminate").
276
+ - **`setSysListener(event, payload, meta)`** — optional, handle custom system events (sent via `helper.emitSys`) on the master; `meta` has `fromWorkerId` and `fromWorkerPid`.
277
+ - **`onFinish(report, helper)`** called once after all workers exit (only when `autoCloseAfterCompletion` is `true`). `report` summarizes the run: `{ taskId, taskFolder, startTimestamp, endTimestamp, cost, total, succeeded, failed, failedTasks, succButSaveFailed, workers }` — `cost` is the run duration in ms (a resumed run measures only the current round); `failedTasks` lists the failed tasks' subids; `succButSaveFailed` counts tasks that ran fine but whose results could not be JSON-serialized; `workers` is `{ count, crashed }` — the configured worker count and how many workers crashed and were replaced. `helper` walks every persisted task result:
278
+ - **`helper.foreachSuccResult((count, task, result) => {})`** — iterate all succeeded results (`results/succ.json`; in `file` mode `results/succ/`); `count` is a 0-based index, `task` is the original task object (`null` if the original task can't be recovered), `result` is the value returned by `processTask` (`undefined` when the task returned nothing; a `{type: 'result_serialize_error', message}` placeholder when the value could not be JSON-serialized).
279
+ - **`helper.foreachErrorResult((count, task, err) => {})`** — iterate all failed results (`results/errors.json`; in `file` mode `results/errors/`); `err` is the persisted error object as-is (`{ex}` / `{subTask, exception}` / `{type: 'timeout', ...}` / `{type: 'worker_crash', ...}`). A non-`Error` rejection value that is not JSON-serializable is persisted as `{ex: {type: 'unserializable_error_value', ...}}`.
280
+ - **`helper.foreachResult((count, task, result, succeeded) => {})`** — iterate all results regardless of outcome (succeeded first, then failed; `count` runs continuously across both); `succeeded` is `true` for succeeded results and `false` for failed ones (where `result` is the persisted error object).
281
+ - In `file` mode the iteration order is unspecified; in `memory` and `aof` modes the helpers iterate in completion order. `onFinish` runs synchronously at the very end and the master process exits shortly after it returns — don't `await` inside it.
282
+
283
+ **Other options:**
284
+
285
+ - **`taskFolder`** — full task folder path; only used by `resume`/`retry_fails`/`restart`.
286
+
287
+ **Task helper** (the `helper` object passed as the second argument of `processTask`):
288
+
289
+ - **`helper.createNewTasks(tasks)`** — create new tasks dynamically while processing.
290
+ - **`helper.emit(event, payload, option?)`** — broadcast an event to all workers (relayed by the master, best-effort); `option.includingMe` defaults to `true` — pass `{includingMe: false}` to exclude the sender. Payload must be JSON-serializable.
291
+ - **`helper.setListener(event, handler)`** — listen for broadcast events; one handler per event per worker process (re-registering replaces it), so calling it inside `processTask` is always safe; `handler(payload, meta)` gets `meta.fromWorkerId` and `meta.fromWorkerPid`. Broadcasts are runtime-only messages — not persisted, not replayed on resume.
292
+ - **`helper.emitSys(event, payload?)`** — send a system event to the master (consumed by the master itself, not relayed). Built-in event: `'TERMINATE_ALL_WORKERS'` force-kills all workers and exits the master; any other event goes to `config.setSysListener`.
293
+
294
+ ### Changelog:
295
+
296
+ - 4.0.0 Add `task_storage: 'aof'` mode (memory-grade speed with full resume) and make it the default — set `task_storage: 'file'` for the classic per-task-file layout (old folders still resume in their own mode); `aof` results are appended to aggregate `results/succ.json`/`errors.json` (one JSON line per task) instead of per-task files
297
+ - 3.5.2 Fix Readme
298
+ - 3.5.1 Fix bench-storage.svg
299
+ - 3.5.0 Add `task_storage: 'memory'` mode (~17x faster, no resume)
300
+ - 3.4.1 Rewrite README: simpler structure, all examples verified by test cases
301
+ - 3.4.0 Show per-worker load (ELU/CPU/memory) under progressBar; stability fixes
302
+ - 3.3.0 Unserializable results still succeed; shouldTerminate throwing is safe; progressBar counters added
303
+ - 3.2.3 Support workerPriority: set OS scheduling priority for worker processes
304
+ - 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
305
+ - 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
306
+ - 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
307
+ - 3.1.9 Print the multi-tasks-monitor command on startup
308
+ - 3.1.8 Small refinements
309
+ - 3.1.7 onFinish: iterate all succ/failed results via helper.foreachSuccResult/foreachErrorResult
310
+ - 3.1.6 Fix silent task loss under heavy load with maxTaskRetries
311
+ - 3.1.4 Rewrite methods multiTasks.resume/retry_fails/restart
312
+ - 3.1.0 Support worker broadcast and system events; default numberOfWorkers is now "50%" of CPU cores
313
+ - 3.0.3 Support 'maxTaskRetries'
314
+ - 3.0.2 Support 'taskTimeout'
315
+ - 3.0.1 Versions 3.0.0 and above are maintained by AI
316
+ - 3.0.0 and earlier: see the git history
317
+
318
+ ### Gitee:
319
+
320
+ [https://gitee.com/zhanglei923/multi-tasks](https://gitee.com/zhanglei923/multi-tasks)
321
+
322
+ ### License:
323
+
324
+ [MIT](https://opensource.org/license/MIT)