-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscheduler.js
152 lines (139 loc) · 4.76 KB
/
scheduler.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
const DAYS = {
sunday: true,
monday: true,
tuesday: true,
wednesday: true,
thursday: true,
friday: true,
saturday: true
};
const {sunday, monday, tuesday, wednesday, thursday, friday, saturday} = DAYS;
const KEYS = Object.keys(DAYS);
const minuteMillis = 60000;
const minimalTimeout = 30 * minuteMillis;
const active = [];
let debug = message => console.log(`scheduler: ${message}`);
async function execute(name, options) {
debug(`Executing '${name}'`);
const {asyncTask} = options || {};
if (asyncTask) {
try {
await asyncTask();
} catch (e) {
debug(`Service '${name}' failed because of ${e}`);
}
}
}
const millisFrom = (days, hours, minutes, seconds, millis) => (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000 + millis;
function millisToNext(now, configuration) {
const {days, time, timestamp, interval} = configuration;
if (interval) {
const timespan = interval * minuteMillis;
return timespan;
}
if (timestamp) {
const timeout = timestamp - now.getTime();
if (timeout >= 0) return timeout;
}
if (time) {
const todayDay = now.getDay();
const {hours = 0, minutes = 0, seconds = 0, millis = 0} = time;
const inHours = hours - now.getHours();
const inMinutes = minutes - now.getMinutes();
const inSeconds = seconds - now.getSeconds();
const inMillis = millis - now.getMilliseconds();
for (let day = 0; day < 8; day++) {
const atDay = (todayDay + day) % 7;
if (!days || days[KEYS[atDay]] === true) {
const timeout = millisFrom(day, inHours, inMinutes, inSeconds, inMillis);
if (timeout >= 0) return timeout;
}
}
}
return -1;
}
function addScheduler(creatingNew, now, name, configuration, options) {
const time = now.getTime();
const inMillis = millisToNext(now, configuration);
if (inMillis >= 0) {
const at = time + inMillis;
const fi = active.findIndex(item => at < item.at);
const index = active.length > 0 ? (fi === -1 ? active.length : fi) : 0; // -1
active.splice(index, 0, {at, name, configuration, options});
handleTimer(creatingNew);
}
return inMillis;
}
function createScheduler(name, configuration, options) {
const now = new Date();
const inMillis = addScheduler(true, now, name, configuration, options);
if (inMillis >= 0) {
const {d, h, m, s} = minutesToDaysHoursMinutesArr(inMillis);
debug(`Scheduled job '${name}' is going to be executed in ${d} days, ${h} hours, ${m} minutes, ${s} seconds`);
}
}
function clearScheduler(name) {
let i = active.length;
let modified = false;
while (i-- > 0) {
if (active[i].name === name) {
active.splice(i, 1);
modified = true;
}
}
if (modified) {
debug(`Canceling previously scheduled job '${name}'`);
handleTimer(true);
}
}
function clearAllSchedulers() {
const {length} = active;
if (length > 0) {
active.splice(0, length);
debug(`Canceling previously scheduled jobs`);
handleTimer(false);
}
}
let timeoutReference = null;
function handleTimer(creatingNew) {
if (timeoutReference != null) {
clearTimeout(timeoutReference);
timeoutReference = null;
}
if (active.length > 0) {
const now = Date.now();
const {at, name, configuration, options} = active[0];
const suggestedTimeout = at - now;
if (suggestedTimeout < 0) {
active.splice(0, 1);
execute(name, options).then(() => {
addScheduler(false, new Date(now), name, configuration, options);
});
} else {
if (!creatingNew) {
const {d, h, m, s} = minutesToDaysHoursMinutesArr(suggestedTimeout);
debug(`Waiting for job '${name}' to be executed in ${d} days, ${h} hours, ${m} minutes, ${s} seconds`);
}
const timeout = Math.min(minimalTimeout, suggestedTimeout);
timeoutReference = setTimeout(() => {
timeoutReference = null;
handleTimer(false);
}, timeout);
}
}
}
function minutesToDaysHoursMinutesArr(inMillis) {
const minutes = Math.floor(inMillis / minuteMillis);
const h = Math.floor(minutes / 60);
const seconds = (inMillis - minutes * minuteMillis) / 1000;
return {d: Math.floor(h / 24), h: h % 24, m: minutes % 60, s: seconds};
}
const setDebug = _debug => debug = _debug;
module.exports = {
//Main methods:
createScheduler, clearScheduler, clearAllSchedulers,
//logger:
setDebug,
//days:
sunday, monday, tuesday, wednesday, thursday, friday, saturday
};