forked from ethstorage/ethfs-uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJTPool.js
99 lines (85 loc) · 2.27 KB
/
JTPool.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const INITIAL = 0;
const RUNNING = 1;
class JTPool {
constructor(maxThread) {
this.status = INITIAL;
this.workQueue = []; // workQueue = [{id: xx, task: xx}]
this.max = (undefined === maxThread) ? 3 : maxThread;
this.current = 0;
}
addTask(task) {
if (undefined === task || typeof task != 'function' || task.length < 1) {
throw Error('Must be a function with a callback parameter. e.g. function(callback) {...}');
}
const timestamp = this._getTimestamp();
this.workQueue.push({ 'id': timestamp, 'task': task });
if (RUNNING === this.status && this.current < this.max) {
this._check();
}
return timestamp;
}
removeTask(id) {
for (const i in this.workQueue) {
if (this.workQueue[i].id === id) {
this.workQueue.splice(i, 1);
break;
}
}
}
clear() {
this.workQueue = [];
}
start() {
if (INITIAL === this.status) {
this.status = RUNNING;
this._check();
}
}
stop() {
if (RUNNING === this.status) {
this.status = INITIAL;
}
}
sleep(timeInMillionSecond) {
const task = function (callback) {
setTimeout(function () {
callback();
}, timeInMillionSecond);
};
this.addTask(task);
}
finish(callback){
this.finishCallback = callback;
}
_notifyComplete() {
this.current--;
this._check();
if (this.finishCallback && this.current === 0) {
this.finishCallback();
}
}
_check() {
let work;
while (RUNNING === this.status && this.current < this.max) {
work = this.workQueue.shift();
if (undefined !== work) {
this.current++;
this._executeTask(work);
} else {
break;
}
}
}
_getTimestamp() {
return new Date().getTime();
}
_executeTask(work) {
const _this = this;
const task = work.task;
task(function () {
_this._notifyComplete();
});
}
}
JTPool.inDebugMode = false;
module.exports = JTPool;