Parse cron expression and compute next run datetime in Python
Parse a 5-field cron expression and compute the next matching datetime starting from a given base time.
Python code
34 linesfrom datetime import datetime, timedelta
import re
def parse_cron_and_next_run(cron_expr, base_time=None):
"""Parse a cron expression and compute the next run time."""
if base_time is None:
base_time = datetime.now().replace(second=0, microsecond=0)
fields = cron_expr.split()
if len(fields) != 5:
raise ValueError("Cron expression must have exactly 5 fields: minute hour day month weekday")
minute, hour, day, month = [int(f) for f in fields[:4]]
weekday = int(fields[4])
candidate = base_time + timedelta(minutes=1)
for _ in range(100000): # safety limit
if candidate.month == month and \
candidate.day == day and \
candidate.hour == hour and \
candidate.minute == minute and \
candidate.weekday() == weekday:
return candidate
candidate += timedelta(minutes=1)
raise ValueError("No matching time found within search limit")
if __name__ == "__main__":
# Example: run at 9:15 AM on Mondays
cron = "15 9 * * 1"
base = datetime(2024, 1, 1, 8, 30) # Monday, Jan 1, 2024 8:30 AM
next_run = parse_cron_and_next_run(cron, base)
print(f"Cron: '{cron}'")
print(f"Base time: {base}")
print(f"Next run: {next_run}")
Output
Cron: '15 9 * * 1'
Base time: 2024-01-01 08:30:00
Next run: 2024-01-08 09:15:00
How it works
The function splits the cron expression into five fields: minute, hour, day, month, and weekday, then converts the first four to integers. It starts from the base time plus one minute and iterates forward minute by minute, checking each candidate against all five constraints. The loop has a safety limit of 100,000 iterations to avoid infinite loops on impossible schedules. When a candidate matches all fields, it's returned as the next run time.
Common mistakes
- Forgetting that weekday 0 is Monday in Python's datetime.weekday()
- Not adding one minute to base_time before searching, missing a run at the exact base time
- Assuming '*' fields mean any value without handling them explicitly
Variations
- Use the `croniter` library for full cron expression support including ranges and steps
- Implement with a list comprehension over candidate times for better readability
Real-world use cases
- Scheduling recurring jobs in a custom task runner where you need to display the next execution time.
- Validating cron-like configuration in deployed services by computing upcoming run times for monitoring dashboards.
- Building an internal tool that syncs with external schedulers and needs to show previews of future job executions.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.