Skip to content
RED SAGSkills

Next Run Time of a Cron Job

Given a cron expression expr and a UTC timestamp afterIso (like 2024-03-08T09:00:00Z, possibly with non-zero seconds), return the first whole minute strictly after afterIso at which the job runs, formatted as YYYY-MM-DDTHH:MM:00Z.

The expression has five fields: minute (0-59), hour (0-23), day of month (1-31), month (1-12) and day of week (0-7, 0 and 7 are Sunday). Each field is a comma-separated list of *, n, a-b, or */a-b followed by /s. Minute, hour and month must match. For the day, if both day-of-month and day-of-week are restricted (anything other than exactly *), either one matching is enough; otherwise both must match.

Search at most 5 years (1830 days) ahead, starting from the day of afterIso. If no run is found, return null.

Example 1

Input: expr = "*/15 * * * *", afterIso = "2024-03-11T09:07:00Z"
Output: "2024-03-11T09:15:00Z"
Explanation: The next quarter hour.

Example 2

Input: expr = "0 9 * * 1-5", afterIso = "2024-03-08T09:00:00Z"
Output: "2024-03-11T09:00:00Z"
Explanation: Friday 09:00 itself is not strictly after, so the next weekday run is Monday.

Constraints

  • expr is valid
  • afterIso is between 1971 and 2094
Hint 1

Do not test every minute; skip whole days that do not match first.

Hint 2

Within a matching day, try the allowed hours and minutes in ascending order.

Discussion 0

Join free to post in the discussion.

Good practice for: Site Reliability Engineer, DevOps Engineer, Cloud Engineer, Backend Developer, Automation Test Engineer, Data Engineer

Run checks your code on 3 sample tests. Submit runs all 10 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.