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 +324 -319
- package/bench-storage.svg +15 -11
- package/package.json +1 -1
- package/utils/makedir.js +5 -4
- package/utils/progressCtl.js +7 -0
- package/utils/runLog.js +7 -2
- package/utils/startupBanner.js +5 -0
- package/workers/AofStore.js +349 -0
- package/workers/MemoryStore.js +337 -247
- package/workers/Multithread.js +92 -53
- package/workers/TaskMgr.js +52 -7
- package/workers/asMaster.js +138 -109
- package/workers/helper.js +77 -77
- package/workers/index.js +282 -224
- package/workers/resultFileAppender.js +62 -0
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
|
|
6
|
-
|
|
7
|
-
![task_storage benchmark: file
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
- **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
|
-
|
|
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
|
-
|
|
280
|
-
|
|
281
|
-
-
|
|
282
|
-
|
|
283
|
-
**
|
|
284
|
-
|
|
285
|
-
- **`
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
-
|
|
297
|
-
- 3.
|
|
298
|
-
- 3.
|
|
299
|
-
- 3.
|
|
300
|
-
- 3.
|
|
301
|
-
- 3.
|
|
302
|
-
- 3.
|
|
303
|
-
- 3.
|
|
304
|
-
- 3.
|
|
305
|
-
- 3.1
|
|
306
|
-
- 3.
|
|
307
|
-
- 3.1.
|
|
308
|
-
- 3.
|
|
309
|
-
- 3.
|
|
310
|
-
- 3.
|
|
311
|
-
- 3.
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
+

|
|
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)
|