index.js
1.56 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
const EventEmitter = require('events');
const path = require('path');
const { fork } = require('child_process');
const uuid = require('uuid');
const daemonPath = `${__dirname}/daemon.js`;
class BackgroundScheduledTask extends EventEmitter {
constructor(cronExpression, taskPath, options){
super();
if(!options){
options = {
scheduled: true,
recoverMissedExecutions: false,
};
}
this.cronExpression = cronExpression;
this.taskPath = taskPath;
this.options = options;
this.options.name = this.options.name || uuid.v4();
if(options.scheduled){
this.start();
}
}
start() {
this.stop();
this.forkProcess = fork(daemonPath);
this.forkProcess.on('message', (message) => {
switch(message.type){
case 'task-done':
this.emit('task-done', message.result);
break;
}
});
let options = this.options;
options.scheduled = true;
this.forkProcess.send({
type: 'register',
path: path.resolve(this.taskPath),
cron: this.cronExpression,
options: options
});
}
stop(){
if(this.forkProcess){
this.forkProcess.kill();
}
}
pid() {
if(this.forkProcess){
return this.forkProcess.pid;
}
}
isRunning(){
return !this.forkProcess.killed;
}
}
module.exports = BackgroundScheduledTask;