How to Mock Cron Schedule in Python

Compute the next scheduled run time for a cron expression using a pure-Python mock parser.

Medium Python 3.9+ Aug 9, 2026 ML engineering pipelines 17 views 0 copies

Python code

42 lines
Python 3.9+
import 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

stdout
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

  1. Use `croniter` library for production-grade parsing
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from ML engineering pipelines

Related tutorials and quizzes for this topic.