How to Mock Cron Schedule in Python
Compute the next scheduled run time for a cron expression using a pure-Python mock parser.
Python code
42 linesimport re
from datetime import datetime, timedelta
class CronMock:
def __init__(self, expression):
self.expression = expression
self.minutes = self._parse_field(expression.split()[0], 0, 59)
self.hours = self._parse_field(expression.split()[1], 0, 23)
self.days = self._parse_field(expression.split()[2], 1, 31)
self.months = self._parse_field(expression.split()[3], 1, 12)
self.dow = self._parse_field(expression.split()[4], 0, 6)
def _parse_field(self, field, low, high):
if field == '*':
return set(range(low, high + 1))
values = set()
for part in field.split(','):
if '-' in part:
start, end = map(int, part.split('-'))
values.update(range(start, end + 1))
elif '/' in part:
base, step = part.split('/')
start = low if base == '*' else int(base)
values.update(range(start, high + 1, int(step)))
else:
values.add(int(part))
return values
def next_run(self, start=None):
now = start or datetime.now()
now = now.replace(second=0, microsecond=0) + timedelta(minutes=1)
for _ in range(525600): # check up to a year ahead
if (now.minute in self.minutes and now.hour in self.hours and
now.day in self.days and now.month in self.months and
now.weekday() in self.dow):
return now
now += timedelta(minutes=1)
return None
if __name__ == "__main__":
cron = CronMock("*/15 9-17 * * 1-5")
print("Next run:", cron.next_run(datetime(2024, 5, 6, 10, 0)))
Output
Next run: 2024-05-06 10:15:00
How it works
The CronMock parses each cron field into a set of allowed values (minutes, hours, days, months, weekdays). next_run increments a datetime by one minute until all fields match, mimicking cron's execution pattern. This avoids external cron libraries and gives a deterministic next-run for testing and scheduling logic.
Common mistakes
- Forgetting to reset seconds and microseconds before iteration
- Assuming cron day-of-week starts at 1 instead of 0
- Not handling combined ranges and steps like `*/15`
- Limiting search to too few iterations, missing rare schedules
Variations
- Use `croniter` library for production-grade parsing
- Precompute all scheduled times in a batch window for efficiency
Real-world use cases
- Testing ML pipeline triggers that should run on a fixed cadence without external cron services.
- Simulating scheduled retraining jobs in a local development environment before deployment.
- Validating cron expressions for data ingestion jobs in a CI/CD pipeline.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.