forked from jchen1/crontab-deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron.ts
201 lines (175 loc) · 5.2 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
type CronJob = {
id: bigint;
schedule: string;
fn: () => any;
};
const days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
const months = [
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"oct",
"nov",
"dec",
];
const cronParts: Record<string, (date: Date) => number> = {
minute: (date) => date.getMinutes(),
hour: (date) => date.getHours(),
dayOfMonth: (date) => date.getDate(),
month: (date) => date.getMonth() + 1,
dayOfWeek: (date) => date.getDay(),
};
function cronPartMatches(now: Date, cronPart: string, part: string) {
const currPart = cronParts[part](now);
// A list is a set of numbers (or ranges) separated by commas.
const opts = cronPart.split(",").map((p) => p.trim());
return opts.some((cronPart) => {
// A field may contain an asterisk, which always stands for "first-last".
if (cronPart === "*") return true;
// exact match
if (cronPart === String(currPart)) return true;
// Names can also be used for the 'month' and 'day of week' fields.
// Use the first three letters of the particular day or month
// (case does not matter)
if (part === "month" && cronPart.toLowerCase() === months[currPart - 1]) {
return true;
}
if (part === "dayOfWeek" && cronPart.toLowerCase() === days[currPart]) {
return true;
}
const rangeMatch = cronPart.match(/(\d+)-(\d+)/);
const stepMatch = cronPart.match(/[\d-*]+\/(\d+)/);
let rangeMatches = true;
let stepMatches = true;
let rangeStart: number | undefined;
let rangeEnd: number | undefined;
if (rangeMatch !== null) {
rangeStart = parseInt(rangeMatch[1]);
rangeEnd = parseInt(rangeMatch[2]);
rangeMatches = rangeStart <= currPart && currPart <= rangeEnd;
}
// Step values can be used in conjunction with ranges.
// Following a range with "/<number>" specifies skips of the
// number's value through the range.
if (stepMatch !== null) {
const step = parseInt(stepMatch[1]);
stepMatches = (currPart - (rangeStart || 0)) % step === 0;
}
if (rangeMatch) {
return rangeMatches && stepMatches;
} else if (stepMatch) {
return stepMatches;
}
return false;
});
}
export function timeForCron(now: Date, schedule: string) {
const crontab = schedule.split(" ");
const matches = Object.keys(cronParts).reduce((acc, k, idx) => {
acc[k] = cronPartMatches(now, crontab[idx], k);
return acc;
}, {} as Record<string, boolean>);
// Note: The day of a command's execution can be specified in the following
// two fields --- 'day of month', and 'day of week'.
// If both fields are restricted (i.e., do not contain the "*" character),
// the command will be run when either field matches the current time.
return (
matches.minute &&
matches.hour &&
matches.month &&
(matches.dayOfMonth || matches.dayOfWeek)
);
}
export class Cron {
private lastest_id = 0n;
private running = true;
jobs: CronJob[];
constructor() {
this.jobs = [];
}
/**
* @param schedule cron syntax to schedule a job
* @param fn a function to execute
* @returns identifier for cron job
*/
add(schedule: string, fn: () => any): bigint {
if (
!schedule.match(/((?:[\d*-/]+|[A-Za-z]{3}) ){4}(?:[\d*-/]+|[A-Za-z]{3})/)
) {
throw new Error(`invalid crontab: ${schedule}!`);
}
const id = this.lastest_id += 1n;
this.jobs.push({ id, schedule, fn });
return id;
}
/**
*
* @param filter a function used to remove jobs if function return true job will be removed
* @param limit number of job to remove default is Number.MAX_VALUE
* @returns removed job
*/
removeBy(filter: (job: CronJob) => boolean, limit = Number.MAX_VALUE): CronJob[] {
const jobs = this.jobs;
const removed = [];
let lim = 0;
for (let index = jobs.length - 1; index >= 0; --index) {
const job = jobs[index];
if (filter(job)) {
const rm = jobs.splice(index, 1);
if (rm.length > 0) {
removed.push(rm[0]);
}
if (++lim == limit) break;
}
}
return removed;
}
/**
* remove job by id
* @param id job id to remove
* @returns removed job
*/
removeById(id: bigint): CronJob | null {
const removed = this.removeBy((job) => job.id == id, 1)
return removed.length == 0 ? null : removed[0];
}
/**
* remove job by schedule
* @param schedule job schedule to remove
* @returns removed jobs
*/
removeBySchedule(schedule: string): CronJob[] {
return this.removeBy((job) => job.schedule == schedule);
}
/**
* remove job by function
* @param fn job fn to remove
* @returns removed jobs
*/
removeByFunction(fn: () => any): CronJob[] {
return this.removeBy((job) => job.fn == fn);
}
stop() {
this.running = false;
}
// deno-lint-ignore require-await
async start() {
if (!this.running) { // this call may schedule by setTimeout
this.running = true;
return;
}
const now = new Date();
setTimeout(() => this.start(), (61 - now.getSeconds()) * 1000);
return Promise.allSettled(
this.jobs
.filter(({ schedule }) => timeForCron(now, schedule))
.map((job) => job.fn()),
);
}
}