Reading — step 1 of 5
Read
~1 min readSchedule Computation
Computing the Next Run Time
next_run(cron, after) returns the smallest datetime > after that matches
the cron expression.
A naive implementation increments by 1 minute and tests matches() each step,
but that's slow for 0 0 1 1 * (yearly). The standard algorithm walks
field-by-field, smallest-to-largest, snapping each component up to the
next allowed value:
1. Increment minute to next allowed (carry if needed).
2. If minute carried, increment hour. If hour > max-allowed, snap to next allowed
hour and reset minute to its smallest allowed value.
3. Similar for day, month, year.
4. Verify matches(); if not (e.g. day-of-week mismatch), advance by a day and retry.
Edge case: years with no matching dates (e.g. * * 30 2 *) should not loop
forever — cap at +4 years and return error.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…