forked from HowProgrammingWorks/IntegrationTesting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduler.js
More file actions
105 lines (94 loc) · 2.21 KB
/
scheduler.js
File metadata and controls
105 lines (94 loc) · 2.21 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
105
'use strict';
const { EventEmitter } = require('events');
const { Logger } = require('./logger.js');
class Task extends EventEmitter {
constructor(name, time, exec) {
super();
this.name = name;
if (typeof time === 'number') {
this.time = Date.now() + time;
this.set = setInterval;
this.clear = clearInterval;
} else {
this.time = new Date(time).getTime();
this.set = setTimeout;
this.clear = clearTimeout;
}
this.exec = exec;
this.running = false;
this.count = 0;
this.timer = null;
}
get active() {
return !!this.timer;
}
start() {
this.stop();
if (this.running) return false;
const time = this.time - Date.now();
if (time < 0) return false;
this.timer = this.set(() => {
this.run();
}, time);
return true;
}
stop() {
if (!this.active || this.running) return false;
this.clear(this.timer);
this.timer = null;
this.emit('stop', this);
return true;
}
run() {
if (!this.active || this.running) return false;
this.running = true;
this.emit('begin', this);
this.exec((err, res) => {
this.count++;
this.emit('end', res, this);
this.running = false;
if (err) this.emit('error', err, this);
});
return true;
}
}
class Scheduler extends EventEmitter {
constructor() {
super();
this.tasks = new Map();
this.logger = new Logger();
}
task(name, time, exec) {
this.stop(name);
const task = new Task(name, time, exec);
this.tasks.set(name, task);
task.on('error', (err) => {
this.logger.error(`${name}\t${err.message}`);
this.emit('error', err, task);
});
task.on('begin', () => {
this.logger.info(`${name}\tbegin`);
});
task.on('end', (res = '') => {
this.logger.info(`${name}\tend\t${res}`);
});
task.on('stop', () => {
this.logger.info(`${name}\tstop`);
});
task.start();
return task;
}
stop(name) {
const task = this.tasks.get(name);
if (!task) return false;
task.stop();
this.tasks.delete(name);
return true;
}
stopAll() {
for (const name of this.tasks.keys()) {
this.stop(name);
}
}
}
module.exports = { Scheduler };