-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcron.ts
168 lines (140 loc) · 4.13 KB
/
cron.ts
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
type JobType = () => void;
enum TIME_PART {
SECOND = 'SECOND',
MINUTE = 'MINUTE',
HOUR = 'HOUR',
DAY_OF_WEEK = 'DAY_OF_WEEK',
DAY_OF_MONTH = 'DAY_OF_MONTH',
MONTH = 'MONTH',
}
const schedules = new Map<string, Array<JobType>>();
let schedulerTimeIntervalID: ReturnType<typeof setInterval> = 0;
let shouldStopRunningScheduler = false;
export const cron = (schedule: string = '', job: JobType) => {
let jobs = schedules.has(schedule)
? [...(schedules.get(schedule) || []), job]
: [job];
schedules.set(schedule, jobs);
};
const isRange = (text: string) => /^\d\d?\-\d\d?$/.test(text);
const getRange = (min: number, max: number) => {
const numRange = [];
let lowerBound = min;
while (lowerBound <= max) {
numRange.push(lowerBound);
lowerBound += 1;
}
return numRange;
};
const { DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, MONTH, SECOND } = TIME_PART;
const getTimePart = (date: Date, type: TIME_PART): number =>
({
[SECOND]: date.getSeconds(),
[MINUTE]: date.getMinutes(),
[HOUR]: date.getHours(),
[MONTH]: date.getMonth() + 1,
[DAY_OF_WEEK]: date.getDay(),
[DAY_OF_MONTH]: date.getDate(),
}[type]);
const isMatched = (date: Date, timeFlag: string, type: TIME_PART): boolean => {
const timePart = getTimePart(date, type);
if (timeFlag === '*') {
return true;
} else if (Number(timeFlag) === timePart) {
return true;
} else if (timeFlag.includes('/')) {
const [_, executeAt = '1'] = timeFlag.split('/');
return timePart % Number(executeAt) === 0;
} else if (timeFlag.includes(',')) {
const list = timeFlag.split(',').map((num: string) => parseInt(num));
return list.includes(timePart);
} else if (isRange(timeFlag)) {
const [start, end] = timeFlag.split('-');
const list = getRange(parseInt(start), parseInt(end));
return list.includes(timePart);
}
return false;
};
export const validate = (schedule: string, date: Date = new Date()) => {
// @ts-ignore
const timeObj: Record<TIME_PART, boolean> = {};
const [
dayOfWeek,
month,
dayOfMonth,
hour,
minute,
second = '01',
] = schedule.split(' ').reverse();
const cronValues = {
[SECOND]: second,
[MINUTE]: minute,
[HOUR]: hour,
[MONTH]: month,
[DAY_OF_WEEK]: dayOfWeek,
[DAY_OF_MONTH]: dayOfMonth,
};
for (const key in cronValues) {
timeObj[key as TIME_PART] = isMatched(
date,
cronValues[key as TIME_PART],
key as TIME_PART,
);
}
const didMatch = Object.values(timeObj).every(Boolean);
return {
didMatch,
entries: timeObj,
};
};
const executeJobs = () => {
const date = new Date();
schedules.forEach((jobs, schedule) => {
if (validate(schedule, date).didMatch) {
jobs.forEach((job) => job());
}
});
};
const runScheduler = () => {
schedulerTimeIntervalID = setInterval(() => {
if (shouldStopRunningScheduler) {
clearInterval(schedulerTimeIntervalID);
return;
}
executeJobs();
}, 1000);
};
export const everyMinute = (cb: JobType) => {
cron(`1 * * * * *`, cb);
};
export const every15Minute = (cb: JobType) => {
cron(`1 */15 * * * *`, cb);
};
export const hourly = (cb: JobType) => {
cron(`1 0 * * * *`, cb);
};
export const daily = (cb: JobType) => {
cron(`1 0 0 * * *`, cb);
};
export const weekly = (cb: JobType, weekDay: string | number = 1) => {
cron(`1 0 0 * * ${weekDay}`, cb);
};
export const biweekly = (cb: JobType) => {
cron(`1 0 0 */14 * *`, cb);
};
export const monthly = (cb: JobType, dayOfMonth: string | number = 1) => {
cron(`1 0 0 ${dayOfMonth} */1 *`, cb);
};
export const yearly = (cb: JobType) => {
cron(`1 0 0 1 1 *`, cb);
};
export const start = () => {
if (shouldStopRunningScheduler) {
shouldStopRunningScheduler = false;
runScheduler();
}
};
export const stop = () => {
shouldStopRunningScheduler = true;
};
runScheduler();