This repository was archived by the owner on Oct 8, 2023. It is now read-only.
forked from node-cron/node-cron
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscheduler.mjs
47 lines (40 loc) · 1.52 KB
/
scheduler.mjs
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
import EventEmitter from 'events';
import TimeMatcher from './time-matcher.mjs';
class Scheduler extends EventEmitter{
constructor(pattern, timezone, autorecover){
super();
this.timeMatcher = new TimeMatcher(pattern, timezone);
this.autorecover = autorecover;
}
start(){
// clear timeout if exists
this.stop();
let lastCheck = process.hrtime();
let lastExecution = this.timeMatcher.apply(new Date());
const matchTime = () => {
const delay = 1000;
const elapsedTime = process.hrtime(lastCheck);
const elapsedMs = (elapsedTime[0] * 1e9 + elapsedTime[1]) / 1e6;
const missedExecutions = Math.floor(elapsedMs / 1000);
for(let i = missedExecutions; i >= 0; i--){
const date = new Date(new Date().getTime() - i * 1000);
let date_tmp = this.timeMatcher.apply(date);
if(lastExecution.getTime() < date_tmp.getTime() && (i === 0 || this.autorecover) && this.timeMatcher.match(date)){
this.emit('scheduled-time-matched', date_tmp);
date_tmp.setMilliseconds(0);
lastExecution = date_tmp;
}
}
lastCheck = process.hrtime();
this.timeout = setTimeout(matchTime, delay);
};
matchTime();
}
stop(){
if(this.timeout){
clearTimeout(this.timeout);
}
this.timeout = null;
}
}
export default Scheduler