src/scheduler/cron.ts
5 KB - Voir le fichier brut
// Five-field cron expressions, evaluated in the owner's time zone (lab 09).
//
// minute (0-59) hour (0-23) day of month (1-31) month (1-12) day of week (0-6, Sun = 0)
// 30 7 * * 1-5
// means 07:30 on weekdays. 7 also means Sunday in the day-of-week field.
//
// Each field accepts "*", numbers, ranges "1-5", lists "1,3,5", and steps "*/15" or "0-30/10".
// As in classic cron, when both day-of-month and day-of-week are restricted, either one matching
// is enough.
//
// Time zones and daylight saving: we walk real instants (UTC minutes) and look at their local
// time in the owner's zone. A local time that does not exist (skipped by a spring-forward) never
// matches; a local time that happens twice (fall-back) matches twice.
export interface CronSchedule {
minutes: Set<number>;
hours: Set<number>;
daysOfMonth: Set<number>;
months: Set<number>;
daysOfWeek: Set<number>;
domRestricted: boolean;
dowRestricted: boolean;
}
const FIELDS: [name: string, min: number, max: number][] = [
['minute', 0, 59],
['hour', 0, 23],
['day of month', 1, 31],
['month', 1, 12],
['day of week', 0, 7],
];
export function parseCron(expression: string): CronSchedule {
const parts = expression.trim().split(/\s+/);
if (parts.length !== 5) {
throw new Error(`cron needs 5 fields (minute hour day month weekday), got "${expression}"`);
}
const sets = parts.map((part, i) => parseField(part, ...FIELDS[i]!));
const dow = sets[4]!;
if (dow.has(7)) {
dow.delete(7);
dow.add(0);
}
return {
minutes: sets[0]!,
hours: sets[1]!,
daysOfMonth: sets[2]!,
months: sets[3]!,
daysOfWeek: dow,
domRestricted: parts[2] !== '*',
dowRestricted: parts[4] !== '*',
};
}
function parseField(field: string, name: string, min: number, max: number): Set<number> {
const values = new Set<number>();
for (const item of field.split(',')) {
const [range = '', stepText] = item.split('/');
const step = stepText === undefined ? 1 : Number(stepText);
if (!Number.isInteger(step) || step < 1) throw new Error(`bad step in ${name}: "${item}"`);
let from: number;
let to: number;
if (range === '*') {
from = min;
to = max;
} else if (range.includes('-')) {
[from, to] = range.split('-').map(Number) as [number, number];
} else {
from = Number(range);
to = stepText === undefined ? from : max;
}
if (!Number.isInteger(from) || !Number.isInteger(to) || from < min || to > max || from > to) {
throw new Error(`bad ${name}: "${item}" (allowed ${min}-${max})`);
}
for (let v = from; v <= to; v += step) values.add(v);
}
return values;
}
interface LocalParts {
year: number;
minute: number;
hour: number;
day: number;
month: number;
weekday: number;
}
const WEEKDAYS: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
const formatters = new Map<string, Intl.DateTimeFormat>();
export function localParts(instant: Date, timezone: string): LocalParts {
let fmt = formatters.get(timezone);
if (!fmt) {
fmt = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
hourCycle: 'h23',
year: 'numeric',
minute: 'numeric',
hour: 'numeric',
day: 'numeric',
month: 'numeric',
weekday: 'short',
});
formatters.set(timezone, fmt);
}
const parts = Object.fromEntries(fmt.formatToParts(instant).map((p) => [p.type, p.value]));
return {
year: Number(parts.year),
minute: Number(parts.minute),
hour: Number(parts.hour),
day: Number(parts.day),
month: Number(parts.month),
weekday: WEEKDAYS[parts.weekday ?? ''] ?? 0,
};
}
function dayMatches(schedule: CronSchedule, p: LocalParts): boolean {
const dom = schedule.daysOfMonth.has(p.day);
const dow = schedule.daysOfWeek.has(p.weekday);
if (schedule.domRestricted && schedule.dowRestricted) return dom || dow;
return dom && dow;
}
const MINUTE = 60_000;
/** The first matching minute strictly after `after`, or undefined within about 400 days. */
export function nextRun(schedule: CronSchedule, after: Date, timezone: string): Date | undefined {
let t = Math.floor(after.getTime() / MINUTE) * MINUTE + MINUTE;
const limit = t + 400 * 24 * 60 * MINUTE;
while (t < limit) {
const p = localParts(new Date(t), timezone);
if (!schedule.months.has(p.month) || !dayMatches(schedule, p)) {
// Jump to the next local midnight (or at least one hour, to stay safe across DST).
t += Math.max(60, (23 - p.hour) * 60 + (60 - p.minute)) * MINUTE;
continue;
}
if (!schedule.hours.has(p.hour)) {
t += (60 - p.minute) * MINUTE;
continue;
}
if (schedule.minutes.has(p.minute)) return new Date(t);
t += MINUTE;
}
return undefined;
}