-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
105 lines (91 loc) · 2.36 KB
/
Copy pathindex.js
File metadata and controls
105 lines (91 loc) · 2.36 KB
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
100
101
102
103
104
var Promise = require('bluebird');
module.exports = createAvalancheWorker;
function createAvalancheWorker(opt) {
if (!opt.getNewJob || (typeof opt.getNewJob !== 'function')) {
throw new Error('The attribute getNewJob method needs to be a function');
}
// optional params
var defaultOptions = {
PENDING_TASKS_LIMIT: 10,
FORCE_WORKER_TIME: 1000 * 60 * 5, // 5 minutes
HEARTBEAT_INTERVAL: 1000 * 1, // 1 second
};
var options = Object.assign(defaultOptions, opt);
var getNewJob = opt.getNewJob;
// Private data
var lastJobDoneDate = new Date();
var numPending = 0;
var moreJobsExist = true;
var interval;
return {
start: start,
stop: stop,
numPending: numPending,
};
//// Functions
function worker() {
var self = this;
if (numPending >= options.PENDING_TASKS_LIMIT) {
return;
}
var currentJob;
numPending++;
getNewJob()
.then(function(job) {
currentJob = job;
if (job) {
moreJobsExist = true;
worker();
return job.process();
}
moreJobsExist = false;
if (typeof options.onNoMoreJobs === 'function') {
options.onNoMoreJobs(numPending - 1);
}
return null;
})
.then(function(result) {
if (!result) { return; }
if (typeof options.onSuccess === 'function') {
options.onSuccess(result, currentJob, new Date(), numPending);
}
worker();
})
.finally(function(data) {
lastJobDoneDate = new Date();
numPending--;
})
.catch(function(error) {
if (typeof options.onError === 'function') {
options.onError(error, currentJob, new Date(), numPending);
}
});
}
function start() {
lastJobDoneDate = new Date();
worker(getNewJob);
heartbeat();
}
function stop() {
clearInterval(interval);
}
function heartbeat() {
interval = setInterval(function() {
if (numPending === 0) {
worker(getNewJob);
} else if (needsReset()) {
reset();
worker(getNewJob);
}
}, options.HEARTBEAT_INTERVAL);
}
function needsReset() {
var then = lastJobDoneDate.getTime();
var now = new Date().getTime();
return (now - then > options.FORCE_WORKER_TIME);
}
function reset(){
numPending = 0;
lastJobDoneDate = new Date();
}
}