multi-tasks 3.4.0 → 3.4.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 +277 -376
- package/package.json +1 -1
- package/utils/backward-v1.js +1 -0
- package/utils/randoms.js +2 -2
- package/utils/resolveWorkers.js +4 -2
package/README.md
CHANGED
|
@@ -1,376 +1,277 @@
|
|
|
1
|
-
# multi-tasks
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
### Install:
|
|
6
|
-
|
|
7
|
-
```
|
|
8
|
-
npm install multi-tasks
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
//
|
|
17
|
-
let
|
|
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
|
-
|
|
278
|
-
|
|
279
|
-
- **`multiTasks(config)`** — run tasks; auto-resumes if the task folder already exists or `initialTasks` points to one.
|
|
280
|
-
- **`multiTasks.resume(config)`** — usually you don't need this: the simplest way to resume is to just run `multiTasks(config)` again, it auto-resumes when the task folder already exists. This method resumes an interrupted run from the task folder alone; pass a config object with `taskFolder` (the full task folder path). The whole config (including `processTask`) is restored from `task_config.json` in that folder; any field you pass overrides the snapshot, and overrides are written back into it.
|
|
281
|
-
- **`multiTasks.retry_fails(config)`** — same as `resume`, and also retries the failed tasks.
|
|
282
|
-
- **`multiTasks.restart(config)`** — wipe the task folder's progress and re-run from scratch; pass a config object with `taskFolder`. The config (including `processTask` and `initialTasks`) is restored from `task_config.json`; any field you pass overrides the snapshot, and overrides are written back into it. **All previous progress and results are deleted.**
|
|
283
|
-
|
|
284
|
-
**Config options:**
|
|
285
|
-
|
|
286
|
-
- **`initialTasks`** — array of task objects, a function returning the array (or a Promise of it — called only once, in the master process; worker processes never call it; see [Performance: runs only once, in the master process](#performance-runs-only-once-in-the-master-process)), or a folder path string to resume from.
|
|
287
|
-
- **`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 cannot be saved because it is not JSON-serializable, the task still counts as succeeded, and a warning shows up in the command line and in monitor tools.
|
|
288
|
-
- **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
|
|
289
|
-
- **`taskId`** — task folder name under `taskRootFolder`.
|
|
290
|
-
- **`numberOfWorkers`** — how many worker processes run in parallel; a number, or a percentage string of CPU cores like `"50%"` (default).
|
|
291
|
-
- **`taskTimeout`** — optional, milliseconds; an overdue task fails with a timeout error.
|
|
292
|
-
- **`maxTaskRetries`** — optional, max times a failed task is auto-retried.
|
|
293
|
-
- **`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.
|
|
294
|
-
- **`progressBar`** — `true` by default: shows a live progress bar in the terminal; set `false` to fall back to plain log output.
|
|
295
|
-
- **`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.
|
|
296
|
-
- **`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.
|
|
297
|
-
- **`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").
|
|
298
|
-
- **`setSysListener(event, payload, meta)`** — optional, handle custom system events (sent via `helper.emitSys`) on the master; `meta` has `fromWorkerId` and `fromWorkerPid`.
|
|
299
|
-
- **`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` lets you walk every persisted task result:
|
|
300
|
-
- **`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 returned value could not be JSON-serialized).
|
|
301
|
-
- **`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', ...}}`.
|
|
302
|
-
- **`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).
|
|
303
|
-
- 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.
|
|
304
|
-
|
|
305
|
-
**Other options:**
|
|
306
|
-
|
|
307
|
-
- **`taskFolder`** — full task folder path; only used by `resume`/`retry_fails`/`restart`.
|
|
308
|
-
|
|
309
|
-
**Task helper** (the `helper` object passed as the second argument of `processTask`):
|
|
310
|
-
|
|
311
|
-
- **`helper.createNewTasks(tasks)`** — create new tasks dynamically while processing.
|
|
312
|
-
- **`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.
|
|
313
|
-
- **`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.
|
|
314
|
-
- **`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`.
|
|
315
|
-
|
|
316
|
-
### Changelog:
|
|
317
|
-
|
|
318
|
-
- 3.4.0 Show per-worker load (ELU/CPU/memory) under progressBar; stability fixes
|
|
319
|
-
- 3.3.0 Unserializable results still succeed; shouldTerminate throwing is safe; progressBar counters added
|
|
320
|
-
- 3.2.3 Support workerPriority: set OS scheduling priority for worker processes
|
|
321
|
-
- 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
|
|
322
|
-
- 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
|
|
323
|
-
- 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
|
|
324
|
-
- 3.1.9 Print the multi-tasks-monitor command on startup
|
|
325
|
-
- 3.1.8 Small refinements
|
|
326
|
-
- 3.1.7 onFinish: iterate all succ/failed results via helper.foreachSuccResult/foreachErrorResult
|
|
327
|
-
- 3.1.6 Fix silent task loss under heavy load with maxTaskRetries
|
|
328
|
-
- 3.1.5 Update README
|
|
329
|
-
- 3.1.4 Rewrite methods multiTasks.resume/retry_fails/restart
|
|
330
|
-
- 3.1.3 Update README
|
|
331
|
-
- 3.1.2 Update README
|
|
332
|
-
- 3.1.1 Fix readme documentation
|
|
333
|
-
- 3.1.0 Support worker broadcast and system events; default numberOfWorkers is now "50%" of CPU cores
|
|
334
|
-
- 3.0.4 numberOfWorkers accepts a percentage string of CPU cores, e.g. "50%"
|
|
335
|
-
- 3.0.3 Support 'maxTaskRetries'
|
|
336
|
-
- 3.0.2 Support 'taskTimeout'
|
|
337
|
-
- 3.0.1 Versions 3.0.0 and above are maintained by AI
|
|
338
|
-
- 2.2.0 Support Resuming from an interrupted task
|
|
339
|
-
- 2.1.2 Update readme
|
|
340
|
-
- 2.1.1 Fix: recreate a new one when a worker collapsed unexpectedly.
|
|
341
|
-
- 2.1.0 Add a new output directory "log" where you can view the process time of each subtask
|
|
342
|
-
- 2.0.9 Update readme examples
|
|
343
|
-
- 2.0.8 Update readme examples
|
|
344
|
-
- 2.0.7 Update changelog
|
|
345
|
-
- 2.0.6 Update readme, remove failed examples
|
|
346
|
-
- 2.0.5 Update readme examples
|
|
347
|
-
- 2.0.4 Support resume from a failed task
|
|
348
|
-
- 2.0.3 Fix: mkdir bug on windows
|
|
349
|
-
- 2.0.2 new feature: support shouldTerminate
|
|
350
|
-
- 2.0.1 Avoid possible I/O conflicts.
|
|
351
|
-
- 2.0.0 Rewritten with a new architecture to support dynamic tasks.
|
|
352
|
-
- 1.2.8 Fix: create task folder failed on MacOS
|
|
353
|
-
- 1.2.7 Small updates
|
|
354
|
-
- 1.2.6 Support onFinish event
|
|
355
|
-
- 1.2.5 Rename numberOfWorks to numberOfWorkers, the old one are still supported ;-)
|
|
356
|
-
- 1.2.4 Fix: opt.numberOfWorkers not work
|
|
357
|
-
- 1.2.3 Update README
|
|
358
|
-
- 1.2.2 Update README and examples
|
|
359
|
-
- 1.2.1 Handle exceptions and errors in subtasks
|
|
360
|
-
- 1.2.0 Simplified usage by providing the function way and support return Promise
|
|
361
|
-
- 1.1.4 Remove make-dir
|
|
362
|
-
- 1.1.3 Simplified usage, see example0
|
|
363
|
-
- 1.1.2
|
|
364
|
-
- 1.1.1 Rename files, updated changelog
|
|
365
|
-
- 1.1.0 Simplified the usage of a customized Consumer, see example0
|
|
366
|
-
- 1.0.8 Fix examples
|
|
367
|
-
- 1.0.7 Remove moment
|
|
368
|
-
- 1.0.6 Performance optimization
|
|
369
|
-
|
|
370
|
-
### Gitee:
|
|
371
|
-
|
|
372
|
-
[https://gitee.com/zhanglei923/multi-tasks](https://gitee.com/zhanglei923/multi-tasks)
|
|
373
|
-
|
|
374
|
-
### License:
|
|
375
|
-
|
|
376
|
-
[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
|
+
### Install:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
npm install multi-tasks
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
### Quick start:
|
|
12
|
+
|
|
13
|
+
```javascript
|
|
14
|
+
let multiTasks = require('multi-tasks').multiTasks;
|
|
15
|
+
|
|
16
|
+
//your tasks, as a plain array
|
|
17
|
+
let tasks = [];
|
|
18
|
+
for(let i = 0; i < 50; i++){
|
|
19
|
+
tasks.push({name: `task-${i}`});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
multiTasks({
|
|
23
|
+
initialTasks: tasks,
|
|
24
|
+
//process one task and return its result (a plain value or a Promise)
|
|
25
|
+
processTask: (task, helper) => {
|
|
26
|
+
return `done: ${task.name}`;
|
|
27
|
+
},
|
|
28
|
+
taskRootFolder: './my-tasks', //progress and results live in ./my-tasks/demo
|
|
29
|
+
taskId: 'demo',
|
|
30
|
+
numberOfWorkers: 3, //worker processes running in parallel
|
|
31
|
+
autoCloseAfterCompletion: true, //exit the process when all tasks are done
|
|
32
|
+
onFinish: (report) => {
|
|
33
|
+
console.log(`${report.succeeded} succeeded, ${report.failed} failed`);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
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`.
|
|
39
|
+
|
|
40
|
+
### Results and errors:
|
|
41
|
+
|
|
42
|
+
`processTask` may return a plain value or a Promise:
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
let processTask = (task, helper) => {
|
|
46
|
+
let {taskCount} = task; //0-based index of this task
|
|
47
|
+
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
setTimeout(() => {
|
|
50
|
+
resolve({data: `task${taskCount} complete`});
|
|
51
|
+
}, 100);
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A failing task never stops the batch — its error is captured and saved to `results/errors`, the rest keep going:
|
|
57
|
+
|
|
58
|
+
```javascript
|
|
59
|
+
let processTask = (task, helper) => {
|
|
60
|
+
let {taskCount} = task;
|
|
61
|
+
|
|
62
|
+
if(taskCount === 3) throw 'exception'; //a thrown value is persisted as-is
|
|
63
|
+
if(taskCount === 4) return Promise.reject({err: 'a test error'}); //a rejection value is persisted as-is
|
|
64
|
+
if(taskCount === 5) aaa = bbb; //a ReferenceError is captured too
|
|
65
|
+
|
|
66
|
+
return {data: 'succ'};
|
|
67
|
+
};
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Creating new tasks dynamically:
|
|
71
|
+
|
|
72
|
+
```javascript
|
|
73
|
+
//scenario: crawl a paginated API — each page tells you if there is a next one
|
|
74
|
+
let processTask = async (task, helper) => {
|
|
75
|
+
let page = await fetchPage(task.url); //your logic here
|
|
76
|
+
|
|
77
|
+
if(page.nextUrl){
|
|
78
|
+
//a discovered next page becomes a new task;
|
|
79
|
+
//the pages are finite, so the queue always drains on its own
|
|
80
|
+
helper.createNewTasks({url: page.nextUrl});
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
return {url: task.url, items: page.items};
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
multiTasks({
|
|
87
|
+
initialTasks: [{url: 'https://api.example.com/items?page=1'}], //start from the first page
|
|
88
|
+
processTask,
|
|
89
|
+
taskRootFolder: './my-tasks',
|
|
90
|
+
taskId: 'api-crawl',
|
|
91
|
+
numberOfWorkers: 3,
|
|
92
|
+
//keep autoCloseAfterCompletion false (the default) while tasks may still be created
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
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.
|
|
97
|
+
|
|
98
|
+
### Timeouts and retries:
|
|
99
|
+
|
|
100
|
+
```javascript
|
|
101
|
+
multiTasks({
|
|
102
|
+
initialTasks: tasks,
|
|
103
|
+
processTask,
|
|
104
|
+
taskRootFolder: './my-tasks',
|
|
105
|
+
taskId: 'demo',
|
|
106
|
+
numberOfWorkers: 3,
|
|
107
|
+
taskTimeout: 30000, //a task that overruns 30s fails with a timeout error
|
|
108
|
+
maxTaskRetries: 2, //auto-retry a failed task (worker crash, processTask error, or timeout) up to 2 times
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Resuming an interrupted run:
|
|
113
|
+
|
|
114
|
+
Just re-run the same code — `multiTasks(config)` detects the existing task folder and auto-resumes, re-running only the stuck tasks:
|
|
115
|
+
|
|
116
|
+
```javascript
|
|
117
|
+
multiTasks(config); //same command, same config as the interrupted run
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Or point `initialTasks` at the task folder — same effect:
|
|
121
|
+
|
|
122
|
+
```javascript
|
|
123
|
+
multiTasks({...config, initialTasks: '/myworks/my_scan_tasks/my-task'});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Or resume from the task folder alone — the config (including `processTask`) is restored from `task_config.json`:
|
|
127
|
+
|
|
128
|
+
```javascript
|
|
129
|
+
multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task'}); //taskFolder: the full path of the existing task folder
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**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:
|
|
133
|
+
|
|
134
|
+
```javascript
|
|
135
|
+
multiTasks.resume({taskFolder: '/myworks/my_scan_tasks/my-task', processTask});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Retrying failed tasks:
|
|
139
|
+
|
|
140
|
+
Resume an interrupted run and also re-run the tasks that failed (in `progress/finished_with_errors`):
|
|
141
|
+
|
|
142
|
+
```javascript
|
|
143
|
+
multiTasks.retry_fails({taskFolder: '/myworks/my_scan_tasks/my-task'});
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Restarting from scratch:
|
|
147
|
+
|
|
148
|
+
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`):
|
|
149
|
+
|
|
150
|
+
```javascript
|
|
151
|
+
multiTasks.restart({taskFolder: '/myworks/my_scan_tasks/my-task'});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
### Broadcasting events between workers:
|
|
157
|
+
|
|
158
|
+
```javascript
|
|
159
|
+
multiTasks({
|
|
160
|
+
initialTasks: tasks,
|
|
161
|
+
processTask: (task, helper) => {
|
|
162
|
+
helper.setListener('task-done', (payload, meta) => {
|
|
163
|
+
console.log(`worker ${meta.fromWorkerPid} says: task ${payload.seq} done`);
|
|
164
|
+
});
|
|
165
|
+
helper.emit('task-done', {seq: task.seq}); //broadcast to all workers
|
|
166
|
+
return {data: 'succ'};
|
|
167
|
+
},
|
|
168
|
+
taskRootFolder: './my-tasks',
|
|
169
|
+
taskId: 'demo',
|
|
170
|
+
numberOfWorkers: 3,
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### System events:
|
|
175
|
+
|
|
176
|
+
Send events from a worker to the master with `helper.emitSys`:
|
|
177
|
+
|
|
178
|
+
```javascript
|
|
179
|
+
multiTasks({
|
|
180
|
+
initialTasks: tasks,
|
|
181
|
+
setSysListener: (event, payload, meta) => {
|
|
182
|
+
console.log(`sys event "${event}" from worker ${meta.fromWorkerPid}:`, payload);
|
|
183
|
+
},
|
|
184
|
+
processTask: (task, helper) => {
|
|
185
|
+
helper.emitSys('task-started', {seq: task.seq});
|
|
186
|
+
if(task.fatal){
|
|
187
|
+
helper.emitSys('TERMINATE_ALL_WORKERS'); //built-in event: stop everything
|
|
188
|
+
return;
|
|
189
|
+
};
|
|
190
|
+
return {data: 'succ'};
|
|
191
|
+
},
|
|
192
|
+
taskRootFolder: './my-tasks',
|
|
193
|
+
taskId: 'demo',
|
|
194
|
+
numberOfWorkers: 3,
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Real-Time Monitoring
|
|
199
|
+
|
|
200
|
+
Monitor your running tasks with [multi-tasks-monitor](https://www.npmjs.com/package/multi-tasks-monitor) — see its npm page for full details.
|
|
201
|
+
|
|
202
|
+
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:
|
|
203
|
+
|
|
204
|
+
```text
|
|
205
|
+
npm install multi-tasks-monitor
|
|
206
|
+
npx multi-tasks-monitor --task-dir "D:\tasks\multitasks20260806..." --port 3777
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### API:
|
|
210
|
+
|
|
211
|
+
**Entry functions:**
|
|
212
|
+
|
|
213
|
+
- **`multiTasks(config)`** — run tasks; auto-resumes if the task folder already exists or `initialTasks` points to one.
|
|
214
|
+
- **`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.
|
|
215
|
+
- **`multiTasks.retry_fails(config)`** — same as `resume`, and also retries the failed tasks.
|
|
216
|
+
- **`multiTasks.restart(config)`** — wipe the task folder's progress and results and re-run from scratch (`{taskFolder}`). **All previous progress and results are deleted.**
|
|
217
|
+
|
|
218
|
+
**Config options:**
|
|
219
|
+
|
|
220
|
+
- **`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.
|
|
221
|
+
- 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.
|
|
222
|
+
- **`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.
|
|
223
|
+
- **`taskRootFolder`** — the task run folder (named by `taskId`) is created under this directory.
|
|
224
|
+
- **`taskId`** — task folder name under `taskRootFolder`.
|
|
225
|
+
- **`numberOfWorkers`** — how many worker processes run in parallel; a number, or a percentage string of CPU cores like `"50%"` (default).
|
|
226
|
+
- **`taskTimeout`** — optional, milliseconds; an overdue task fails with a timeout error.
|
|
227
|
+
- **`maxTaskRetries`** — optional, max times a failed task is auto-retried.
|
|
228
|
+
- **`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.
|
|
229
|
+
- **`progressBar`** — `true` by default: shows a live progress bar in the terminal; set `false` to fall back to plain log output.
|
|
230
|
+
- **`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.
|
|
231
|
+
- **`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.
|
|
232
|
+
- **`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").
|
|
233
|
+
- **`setSysListener(event, payload, meta)`** — optional, handle custom system events (sent via `helper.emitSys`) on the master; `meta` has `fromWorkerId` and `fromWorkerPid`.
|
|
234
|
+
- **`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:
|
|
235
|
+
- **`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).
|
|
236
|
+
- **`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', ...}}`.
|
|
237
|
+
- **`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).
|
|
238
|
+
- 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.
|
|
239
|
+
|
|
240
|
+
**Other options:**
|
|
241
|
+
|
|
242
|
+
- **`taskFolder`** — full task folder path; only used by `resume`/`retry_fails`/`restart`.
|
|
243
|
+
|
|
244
|
+
**Task helper** (the `helper` object passed as the second argument of `processTask`):
|
|
245
|
+
|
|
246
|
+
- **`helper.createNewTasks(tasks)`** — create new tasks dynamically while processing.
|
|
247
|
+
- **`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.
|
|
248
|
+
- **`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.
|
|
249
|
+
- **`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`.
|
|
250
|
+
|
|
251
|
+
### Changelog:
|
|
252
|
+
|
|
253
|
+
- 3.4.1 Rewrite README: simpler structure, all examples verified by test cases
|
|
254
|
+
- 3.4.0 Show per-worker load (ELU/CPU/memory) under progressBar; stability fixes
|
|
255
|
+
- 3.3.0 Unserializable results still succeed; shouldTerminate throwing is safe; progressBar counters added
|
|
256
|
+
- 3.2.3 Support workerPriority: set OS scheduling priority for worker processes
|
|
257
|
+
- 3.2.2 initialTasks accepts a function (sync or async) that is called only once, in the master process
|
|
258
|
+
- 3.2.1 Fix retry bug: user-defined taskCount/index no longer overwritten on task retries
|
|
259
|
+
- 3.2.0 Add progressBar (on by default); console output diverted to run.log; new startup banner
|
|
260
|
+
- 3.1.9 Print the multi-tasks-monitor command on startup
|
|
261
|
+
- 3.1.8 Small refinements
|
|
262
|
+
- 3.1.7 onFinish: iterate all succ/failed results via helper.foreachSuccResult/foreachErrorResult
|
|
263
|
+
- 3.1.6 Fix silent task loss under heavy load with maxTaskRetries
|
|
264
|
+
- 3.1.4 Rewrite methods multiTasks.resume/retry_fails/restart
|
|
265
|
+
- 3.1.0 Support worker broadcast and system events; default numberOfWorkers is now "50%" of CPU cores
|
|
266
|
+
- 3.0.3 Support 'maxTaskRetries'
|
|
267
|
+
- 3.0.2 Support 'taskTimeout'
|
|
268
|
+
- 3.0.1 Versions 3.0.0 and above are maintained by AI
|
|
269
|
+
- 3.0.0 and earlier: see the git history
|
|
270
|
+
|
|
271
|
+
### Gitee:
|
|
272
|
+
|
|
273
|
+
[https://gitee.com/zhanglei923/multi-tasks](https://gitee.com/zhanglei923/multi-tasks)
|
|
274
|
+
|
|
275
|
+
### License:
|
|
276
|
+
|
|
277
|
+
[MIT](https://opensource.org/license/MIT)
|
package/package.json
CHANGED
package/utils/backward-v1.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
function v1tov2(config) {
|
|
2
|
+
if(!config) throw new Error('config is required');//缺参时给有语义的报错, 而不是裸 TypeError(兼容入口 multiTasks/resume/retry_fails/restart 都汇到这里)
|
|
2
3
|
if(config.multi_task_parent_folder && !config.taskRootFolder) config.taskRootFolder = config.multi_task_parent_folder;//backward compatible
|
|
3
4
|
delete config.multi_task_parent_folder;
|
|
4
5
|
|
package/utils/randoms.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
const crypto = require('crypto');
|
|
3
3
|
const fmtDigit = (n)=>{
|
|
4
4
|
return n > 9 ? "" + n: "0" + n;
|
|
5
|
-
}
|
|
5
|
+
};
|
|
6
6
|
const getDateTimeTxt = ()=>{
|
|
7
7
|
let d=new Date();
|
|
8
|
-
let YYYY=d.getFullYear()
|
|
8
|
+
let YYYY=d.getFullYear();
|
|
9
9
|
let MM=fmtDigit(d.getMonth()+1);
|
|
10
10
|
let DD=fmtDigit(d.getDate());
|
|
11
11
|
let HH=fmtDigit(d.getHours());
|
package/utils/resolveWorkers.js
CHANGED
|
@@ -6,7 +6,7 @@ const PERCENT_PATTERN = /^(\d+(?:\.\d+)?)%$/;
|
|
|
6
6
|
|
|
7
7
|
// 解析 numberOfWorkers 配置:
|
|
8
8
|
// - undefined -> 默认 "50%", 按核数四舍五入折算, 最小为 1;
|
|
9
|
-
// - number ->
|
|
9
|
+
// - number -> 必须是 >=1 的整数(0 会静默起不来 worker、小数/负数行为隐晦, fail-fast);
|
|
10
10
|
// - string -> 必须是 "数字%" 形式且百分比在 1-100 之间, 按核数四舍五入折算, 最小为 1;
|
|
11
11
|
// - 其余 -> 抛 Error。
|
|
12
12
|
const percentToWorkers = (percent) => {
|
|
@@ -18,7 +18,9 @@ const resolveNumberOfWorkers = (value) => {
|
|
|
18
18
|
return percentToWorkers(50);
|
|
19
19
|
};
|
|
20
20
|
if (typeof value === 'number') {
|
|
21
|
-
|
|
21
|
+
if (Number.isInteger(value) && value >= 1) {
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
22
24
|
};
|
|
23
25
|
if (typeof value === 'string') {
|
|
24
26
|
const match = value.trim().match(PERCENT_PATTERN);
|