Cron Expression: Next Runs
Hard · Tooling
Scheduled jobs in Node.js (node-cron, node-schedule, cloud schedulers) are configured with cron expressions. Write nextRuns(expr, fromIso, count) that returns the next count run times.
An expression has 5 fields separated by spaces: minute (0-59), hour (0-23), day of month (1-31), month (1-12) and day of week (0-7, where both 0 and 7 mean Sunday). Each field is a comma-separated list of:
- * (every value), a number 5, or a range 1-5 (both ends included),
- optionally followed by a step: */15 or 10-40/10 means every 15th/10th value starting at the start of the range. A step after a single number (like 5/15) is not allowed.
A time matches when the minute, hour and month match and the day matches. The day rule is the classic Vixie cron rule: if the day-of-month field or the day-of-week field starts with *, both must match (so the other one decides). If both are restricted, a day matches when either matches. Example: 0 0 1,15 * 5 runs on the 1st, the 15th and every Friday.
- All times are UTC. Return ISO strings like "2024-03-08T17:00:00.000Z" (use toISOString()), in order.
- Runs must be strictly after fromIso. Seconds in fromIso are allowed; runs are always on whole minutes.
- Stop searching at the start of the year fromYear + 10 (UTC). Return the runs found so far, which can be fewer than count (or [] for a schedule like February 30th).
- Return null if the expression is invalid: not exactly 5 fields, a value out of range, a range whose start is bigger than its end, a step of 0, or any other syntax.
Tip: checking minute by minute for 10 years is slow. Skip whole months, days and hours that cannot match.