Every backend engineer has stared at a crontab line like */15 9-17 * * 1-5 during a production incident and wondered: "Wait - does this run at 17:45 or stop at 17:00? And is Sunday 0 or 7?"
Most apps pull in a heavyweight npm cron package just to validate user-entered schedules or preview the next 5 execution timestamps in a dashboard. Yet standard 5-field POSIX cron syntax (minute hour day-of-month month day-of-week) can be parsed, validated, and simulated in ~70 lines of zero-dependency TypeScript.
Here is a clean, production-safe implementation that handles all five common cron gotchas properly.
5 Cron Edge Cases That Break Naive Parsers
| Cron Expression | Naive Bug | Proper POSIX Handling |
|---|---|---|
0 0 * * 7 |
Rejects 7 as out of range |
Normalize 7 -> 0 (both mean Sunday) |
*/15 9-17 * * 1-5 |
Stops at 17:00
|
Runs 17:00, 17:15, 17:30, 17:45
|
0 9 15 * 1 |
Uses AND (15th AND Monday) |
POSIX uses OR when both DOM & DOW are restricted! |
0 2 30 2 * |
Infinite loop searching for Feb 30 | Hard search cap (4-year leap-year ceiling) |
5-30/10 * * * * |
Only supports */step
|
Supports start-end/step (5, 15, 25) |
That third row (DOM vs DOW) is the single most infamous cron surprise in Linux history: when both Day-of-Month and Day-of-Week are non-wildcard (!= "*"), standard Vixie cron triggers if either field matches!
The Complete 70-Line Zero-Dependency TypeScript Parser
This module runs in Node.js, Bun, Deno, Cloudflare Workers, or directly inside the browser with zero dependencies:
export interface ParsedCron {
minute: Set<number>;
hour: Set<number>;
dom: Set<number>;
month: Set<number>;
dow: Set<number>;
domWildcard: boolean;
dowWildcard: boolean;
}
function parseField(
raw: string,
min: number,
max: number,
normalizeSunday = false
): Set<number> {
const out = new Set<number>();
for (const part of raw.split(",")) {
const [rangePart, stepStr] = part.split("/");
const step = stepStr ? Number(stepStr) : 1;
if (!Number.isInteger(step) || step <= 0) {
throw new Error(`Invalid cron step: "${part}"`);
}
let start = min;
let end = max;
if (rangePart !== "*") {
if (rangePart.includes("-")) {
const [a, b] = rangePart.split("-").map(Number);
start = a;
end = b;
} else {
start = Number(rangePart);
end = stepStr ? max : start;
}
}
const upperBound = normalizeSunday ? 7 : max;
if (
!Number.isInteger(start) ||
!Number.isInteger(end) ||
start < min ||
end > upperBound ||
start > end
) {
throw new Error(`Out-of-range cron value: "${part}"`);
}
for (let v = start; v <= end; v += step) {
out.add(normalizeSunday && v === 7 ? 0 : v);
}
}
return out;
}
export function parseCron(expression: string): ParsedCron {
const parts = expression.trim().split(/\s+/);
if (parts.length !== 5) {
throw new Error(`Expected 5 cron fields, got ${parts.length}`);
}
const [minStr, hrStr, domStr, monStr, dowStr] = parts;
return {
minute: parseField(minStr, 0, 59),
hour: parseField(hrStr, 0, 23),
dom: parseField(domStr, 1, 31),
month: parseField(monStr, 1, 12),
dow: parseField(dowStr, 0, 6, true),
domWildcard: domStr === "*",
dowWildcard: dowStr === "*",
};
}
export function getNextRuns(
expression: string,
count = 5,
fromDate = new Date()
): Date[] {
const cron = parseCron(expression);
const results: Date[] = [];
// Start at the next whole UTC minute to avoid DST jumps
const cursor = new Date(fromDate.getTime());
cursor.setUTCSeconds(0, 0);
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
const maxMinutes = 4 * 366 * 24 * 60; // 4-year cap covers Feb 29
for (let i = 0; i < maxMinutes && results.length < count; i++) {
const mon = cursor.getUTCMonth() + 1;
const dom = cursor.getUTCDate();
const dow = cursor.getUTCDay();
const hr = cursor.getUTCHours();
const min = cursor.getUTCMinutes();
const dayMatch =
cron.domWildcard && cron.dowWildcard
? true
: cron.domWildcard
? cron.dow.has(dow)
: cron.dowWildcard
? cron.dom.has(dom)
: cron.dom.has(dom) || cron.dow.has(dow); // POSIX OR rule!
if (
cron.month.has(mon) &&
dayMatch &&
cron.hour.has(hr) &&
cron.minute.has(min)
) {
results.push(new Date(cursor.getTime()));
}
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
}
return results;
}
Testing Real-World Schedules
console.log(
getNextRuns("*/15 9-17 * * 1-5", 3, new Date("2026-11-30T08:50:00Z"))
.map((d) => d.toISOString())
);
// [
// "2026-11-30T09:00:00.000Z",
// "2026-11-30T09:15:00.000Z",
// "2026-11-30T09:30:00.000Z"
// ]
// Sunday normalized cleanly whether written as 0 or 7:
console.log(parseCron("0 6 * * 7").dow.has(0)); // true
Performance Tip: Fast-Forwarding by Month & Day
The simple minute-by-minute loop above is already sub-millisecond for everyday schedules. If you build an API that evaluates rare schedules (like 0 0 29 2 * - Leap Day only), add three 2-line jumps inside the loop:
- If
!cron.month.has(mon), jumpcursorstraight to the 1st of the next month at00:00 UTC. - If
!dayMatch, jumpcursorto the next day at00:00 UTC. - If
!cron.hour.has(hr), jumpcursorto the next hour at minute00.
With those three jumps, even a Leap-Day schedule resolves in under 0.2 milliseconds.
Try It Visually in Your Browser
If you want to build, decode, and sanity-check 5-part crontab expressions visually before deploying them to Linux, GitHub Actions, or Kubernetes CronJobs, you can try the free client-side Cron Expression Generator & Explainer on OmniTools (zero signup, runs locally in your browser). And if you are debugging log patterns alongside your cron jobs, our Regex Visualizer & Tester pairs nicely with it.
What is the gnarliest cron bug you have ever hit in production (DST shift, Sunday 0 vs 7, or the DOM/DOW OR trap)? Drop it in the comments!
Top comments (0)