multi-tasks 3.4.1 → 3.5.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 +326 -277
- package/bench-storage.svg +17 -0
- package/package.json +3 -2
- package/utils/startupBanner.js +51 -51
- package/workers/IpcTaskStore.js +136 -0
- package/workers/MemoryStore.js +247 -0
- package/workers/Multithread.js +203 -49
- package/workers/TaskMgr.js +406 -406
- package/workers/asMaster.js +109 -101
- package/workers/helper.js +77 -67
- package/workers/index.js +28 -0
package/README.md
CHANGED
|
@@ -1,277 +1,326 @@
|
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
`
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
```
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
-
|
|
247
|
-
|
|
248
|
-
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
-
|
|
260
|
-
-
|
|
261
|
-
-
|
|
262
|
-
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
-
|
|
267
|
-
-
|
|
268
|
-
-
|
|
269
|
-
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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
|
+

|
|
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
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
- **`file`** (default) — every state change hits disk immediately; resume anytime.
|
|
177
|
+
- **`memory`** — task states, results, logs and user messages live in the master process's memory only; no per-task files are ever written. The task folder is still created with the usual subfolders (`progress`/`results`/`logs` stay empty), holding only `task_config.json` and `.sys/run.log`. Dramatically faster for large batches of small tasks — about 20x faster in benchmarks. Results are still available through `onFinish(report, helper)`. `resume`/`retry_fails`/`restart` are not supported for this mode and throw when called — a killed run is simply gone.
|
|
178
|
+
|
|
179
|
+
Benchmark — 30,000 tiny tasks × 28 workers, average of 3 runs on the same machine (17–27× across repeated benchmark sessions):
|
|
180
|
+
|
|
181
|
+

|
|
182
|
+
|
|
183
|
+
**Getting results out in `memory` mode**: since nothing per-task hits disk, `onFinish(report, helper)` is the one and only exit for your data — iterate everything with `helper.foreachResult` (or `foreachSuccResult`/`foreachErrorResult`) and persist it yourself in one batch if you need it kept:
|
|
184
|
+
|
|
185
|
+
```javascript
|
|
186
|
+
onFinish: (report, helper) => {
|
|
187
|
+
helper.foreachResult((count, task, result, succeeded) => {
|
|
188
|
+
//collect / batch-insert / write out — all results are here in memory
|
|
189
|
+
});
|
|
190
|
+
},
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
If you need per-task files anyway, write them in bulk from `onFinish` — do **not** `writeFileSync` inside `processTask`: in benchmarks (30,000 tasks × 28 workers) per-task self-written files made the run ~3.3× slower than pure `memory` (27.7s vs 8.4s), because disk writes still dominate even without the library's bookkeeping. (That said, even the slow do-it-yourself variant beats `file` mode's ~195s — its cost is the resumable state machine, not the writes alone.)
|
|
194
|
+
|
|
195
|
+
Caveats of `memory` mode:
|
|
196
|
+
|
|
197
|
+
- **Monitoring**: [multi-tasks-monitor](#real-time-monitoring) reads the task folder, so it has nothing to show for a `memory` run (no task states/results on disk).
|
|
198
|
+
- **Worker crashes**: without `maxTaskRetries`, a crashed worker's in-flight task is not retried — with `file` it stays in `running` until a later `resume` picks it up; with `memory` it is lost for good.
|
|
199
|
+
- **Dynamic tasks**: with `memory`, `helper.createNewTasks` reaches the master over IPC; if the master is killed before applying them, tasks created but not yet applied are lost. (`file` mode writes them to disk from the worker directly.)
|
|
200
|
+
- **Dynamic tasks with `autoCloseAfterCompletion`**: in `memory` mode the master pops straight from the in-memory queue — there is no on-disk re-read fallback like in `file` mode, and no settle delay before killing an idle worker. A task another worker just sent via `helper.createNewTasks` may still be in IPC transit when the master decides the queue is empty, so it can miss the dispatch window and the workers get closed. If your workers create tasks dynamically, keep `autoCloseAfterCompletion` at its default `false`.
|
|
201
|
+
|
|
202
|
+
### Broadcasting events between workers:
|
|
203
|
+
|
|
204
|
+
```javascript
|
|
205
|
+
multiTasks({
|
|
206
|
+
initialTasks: tasks,
|
|
207
|
+
processTask: (task, helper) => {
|
|
208
|
+
helper.setListener('task-done', (payload, meta) => {
|
|
209
|
+
console.log(`worker ${meta.fromWorkerPid} says: task ${payload.seq} done`);
|
|
210
|
+
});
|
|
211
|
+
helper.emit('task-done', {seq: task.seq}); //broadcast to all workers
|
|
212
|
+
return {data: 'succ'};
|
|
213
|
+
},
|
|
214
|
+
taskRootFolder: './my-tasks',
|
|
215
|
+
taskId: 'demo',
|
|
216
|
+
numberOfWorkers: 3,
|
|
217
|
+
});
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### System events:
|
|
221
|
+
|
|
222
|
+
Send events from a worker to the master with `helper.emitSys`:
|
|
223
|
+
|
|
224
|
+
```javascript
|
|
225
|
+
multiTasks({
|
|
226
|
+
initialTasks: tasks,
|
|
227
|
+
setSysListener: (event, payload, meta) => {
|
|
228
|
+
console.log(`sys event "${event}" from worker ${meta.fromWorkerPid}:`, payload);
|
|
229
|
+
},
|
|
230
|
+
processTask: (task, helper) => {
|
|
231
|
+
helper.emitSys('task-started', {seq: task.seq});
|
|
232
|
+
if(task.fatal){
|
|
233
|
+
helper.emitSys('TERMINATE_ALL_WORKERS'); //built-in event: stop everything
|
|
234
|
+
return;
|
|
235
|
+
};
|
|
236
|
+
return {data: 'succ'};
|
|
237
|
+
},
|
|
238
|
+
taskRootFolder: './my-tasks',
|
|
239
|
+
taskId: 'demo',
|
|
240
|
+
numberOfWorkers: 3,
|
|
241
|
+
});
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### Real-Time Monitoring
|
|
245
|
+
|
|
246
|
+
Monitor your running tasks with [multi-tasks-monitor](https://www.npmjs.com/package/multi-tasks-monitor) — see its npm page for full details.
|
|
247
|
+
|
|
248
|
+
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:
|
|
249
|
+
|
|
250
|
+
```text
|
|
251
|
+
npm install multi-tasks-monitor
|
|
252
|
+
npx multi-tasks-monitor --task-dir "D:\tasks\multitasks20260806..." --port 3777
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### API:
|
|
256
|
+
|
|
257
|
+
**Entry functions:**
|
|
258
|
+
|
|
259
|
+
- **`multiTasks(config)`** — run tasks; auto-resumes if the task folder already exists or `initialTasks` points to one.
|
|
260
|
+
- **`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.
|
|
261
|
+
- **`multiTasks.retry_fails(config)`** — same as `resume`, and also retries the failed tasks.
|
|
262
|
+
- **`multiTasks.restart(config)`** — wipe the task folder's progress and results and re-run from scratch (`{taskFolder}`). **All previous progress and results are deleted.**
|
|
263
|
+
|
|
264
|
+
**Config options:**
|
|
265
|
+
|
|
266
|
+
- **`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.
|
|
267
|
+
- 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.
|
|
268
|
+
- **`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.
|
|
269
|
+
- **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
|
|
270
|
+
- **`taskId`** — task folder name under `taskRootFolder`.
|
|
271
|
+
- **`numberOfWorkers`** — how many worker processes run in parallel; a number, or a percentage string of CPU cores like `"50%"` (default).
|
|
272
|
+
- **`taskTimeout`** — optional, milliseconds; an overdue task fails with a timeout error.
|
|
273
|
+
- **`maxTaskRetries`** — optional, max times a failed task is auto-retried.
|
|
274
|
+
- **`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.
|
|
275
|
+
- **`progressBar`** — `true` by default: shows a live progress bar in the terminal; set `false` to fall back to plain log output.
|
|
276
|
+
- **`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.
|
|
277
|
+
- **`task_storage`** — `'file'` (default) | `'memory'`: where task states and results are kept; see "Task storage modes".
|
|
278
|
+
- **`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.
|
|
279
|
+
- **`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").
|
|
280
|
+
- **`setSysListener(event, payload, meta)`** — optional, handle custom system events (sent via `helper.emitSys`) on the master; `meta` has `fromWorkerId` and `fromWorkerPid`.
|
|
281
|
+
- **`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:
|
|
282
|
+
- **`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).
|
|
283
|
+
- **`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', ...}}`.
|
|
284
|
+
- **`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).
|
|
285
|
+
- Iteration follows filesystem order (not sorted). `onFinish` runs synchronously at the very end and the master process exits shortly after it returns — don't `await` inside it. In `memory` mode the helpers iterate the in-memory results the same way (in completion order).
|
|
286
|
+
|
|
287
|
+
**Other options:**
|
|
288
|
+
|
|
289
|
+
- **`taskFolder`** — full task folder path; only used by `resume`/`retry_fails`/`restart`.
|
|
290
|
+
|
|
291
|
+
**Task helper** (the `helper` object passed as the second argument of `processTask`):
|
|
292
|
+
|
|
293
|
+
- **`helper.createNewTasks(tasks)`** — create new tasks dynamically while processing.
|
|
294
|
+
- **`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.
|
|
295
|
+
- **`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.
|
|
296
|
+
- **`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`.
|
|
297
|
+
|
|
298
|
+
### Changelog:
|
|
299
|
+
|
|
300
|
+
- 3.5.1 Fix bench-storage.svg
|
|
301
|
+
- 3.5.0 Add `task_storage: 'memory'` mode (~17x faster, no resume)
|
|
302
|
+
- 3.4.1 Rewrite README: simpler structure, all examples verified by test cases
|
|
303
|
+
- 3.4.0 Show per-worker load (ELU/CPU/memory) under progressBar; stability fixes
|
|
304
|
+
- 3.3.0 Unserializable results still succeed; shouldTerminate throwing is safe; progressBar counters added
|
|
305
|
+
- 3.2.3 Support workerPriority: set OS scheduling priority for worker processes
|
|
306
|
+
- 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
|
|
307
|
+
- 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
|
|
308
|
+
- 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
|
|
309
|
+
- 3.1.9 Print the multi-tasks-monitor command on startup
|
|
310
|
+
- 3.1.8 Small refinements
|
|
311
|
+
- 3.1.7 onFinish: iterate all succ/failed results via helper.foreachSuccResult/foreachErrorResult
|
|
312
|
+
- 3.1.6 Fix silent task loss under heavy load with maxTaskRetries
|
|
313
|
+
- 3.1.4 Rewrite methods multiTasks.resume/retry_fails/restart
|
|
314
|
+
- 3.1.0 Support worker broadcast and system events; default numberOfWorkers is now "50%" of CPU cores
|
|
315
|
+
- 3.0.3 Support 'maxTaskRetries'
|
|
316
|
+
- 3.0.2 Support 'taskTimeout'
|
|
317
|
+
- 3.0.1 Versions 3.0.0 and above are maintained by AI
|
|
318
|
+
- 3.0.0 and earlier: see the git history
|
|
319
|
+
|
|
320
|
+
### Gitee:
|
|
321
|
+
|
|
322
|
+
[https://gitee.com/zhanglei923/multi-tasks](https://gitee.com/zhanglei923/multi-tasks)
|
|
323
|
+
|
|
324
|
+
### License:
|
|
325
|
+
|
|
326
|
+
[MIT](https://opensource.org/license/MIT)
|