scheduled-task.js
1.2 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
'use strict';
const EventEmitter = require('events');
const Task = require('./task');
const Scheduler = require('./scheduler');
const uuid = require('uuid');
class ScheduledTask extends EventEmitter {
constructor(cronExpression, func, options) {
super();
if(!options){
options = {
scheduled: true,
recoverMissedExecutions: false
};
}
this.options = options;
this.options.name = this.options.name || uuid.v4();
this._task = new Task(func);
this._scheduler = new Scheduler(cronExpression, options.timezone, options.recoverMissedExecutions);
this._scheduler.on('scheduled-time-matched', (now) => {
this.now(now);
});
if(options.scheduled !== false){
this._scheduler.start();
}
if(options.runOnInit === true){
this.now('init');
}
}
now(now = 'manual') {
let result = this._task.execute(now);
this.emit('task-done', result);
}
start() {
this._scheduler.start();
}
stop() {
this._scheduler.stop();
}
}
module.exports = ScheduledTask;