-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjob.interval.js
More file actions
64 lines (55 loc) · 1.79 KB
/
job.interval.js
File metadata and controls
64 lines (55 loc) · 1.79 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
const Job = require('./job');
const moment = require('moment');
/**
* @typedef {object} IntervalJobConfig
* @extends {JobConfig}
* @property {boolean} [waitForComplete=true] For interval jobs whether to wait for finish before calculating next run
* @property {string|number} interval Either a number that represents ms or a string that is readable by moment.js
*/
const momentRegexp = /(\d+)(.*)/;
class IntervalJob extends Job {
/**
* @param {IntervalJobConfig} jobConfig
* @param {JobExecutor} executor
*/
constructor(jobConfig, executor) {
super(jobConfig, executor);
jobConfig.interval = IntervalJob._toInterval(jobConfig.interval);
}
run() {
super.run().then(context => {
if (this._config.waitForComplete) {
this._lastRun = context.ended;
}
setTimeout(this.run.bind(this), this.nextRun);
});
}
/**
* Returns the time (ms) until the next job of this id should run.
* @returns {number}
* @private
*/
get nextRun() {
if (!this._lastRun) {
return this._config.sleep;
}
return Math.max(this._lastRun.valueOf() + this._config.interval - Date.now(), super.nextRun);
}
/**
* Will try to convert the incoming value to a ms interval number.
* @param {*} val
* @returns {number}
* @private
*/
static _toInterval(val) {
switch(typeof val) {
case 'string':
let args = momentRegexp.exec(val).splice(1);
args[0] = parseInt(args);
return moment.duration(...args).asMilliseconds();
case 'number': return val;
default: return moment.duration(val).asMilliseconds();
}
}
}
module.exports = IntervalJob;