-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadpool-es.js
84 lines (76 loc) · 2.27 KB
/
threadpool-es.js
1
2
3
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
/* eslint-env node */
import { writeFile } from 'fs'
class ThreadPool {
constructor(poolSize) {
this.size = poolSize || 20;
this.running = 0;
this.waittingTasks = [];
this.callback = [];
this.tasks = [];
this.counter = 0;
this.sum = 0;
this.finished = false;
this.errorLog = '';
this.step = () => {};
this.timer = null;
this.callback.push(() => writeFile('pool-error.log', this.errorLog, () => {}));
}
status () {
return (this.counter / this.sum * 100).toFixed(1) + '%';
}
run () {
if (this.finished)
return;
if (this.waittingTasks.length === 0)
if (this.running <= 0) {
for (let m = 0; m < this.callback.length; ++m)
this.callback[m] && this.callback[m]();
this.finished = true;
}
else
return;
while (this.running < this.size) {
if (this.waittingTasks.length === 0)
return;
let curTask = this.waittingTasks[0];
curTask.do().then(
onSucceed => {
this.running--;
this.counter++;
this.step();
this.run();
typeof onSucceed === 'function' && onSucceed();
}, onFailed => {
this.errorLog += onFailed + '\n';
this.running--;
this.counter++;
this.step();
this.run();
curTask.err();
}
);
this.waittingTasks.splice(0, 1);
this.tasks.push(this.waittingTasks[0]);
this.running++;
}
}
add (fn, errFn) {
this.waittingTasks.push({ do: fn, err: errFn || (() => {}) });
this.sum++;
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.run();
clearTimeout(this.timer);
}, this.autoStartTime);
}
setAutoStart(time) {
this.autoStartTime = time;
}
finish(callback) {
this.callback.push(callback);
}
isFinished() {
return this.finished;
}
}
export default ThreadPool