Gauntlet 05: Cron Expression Evaluator
Cron expressions evaluate recurring schedules across five fields: minute, hour, day-of-month, month, and day-of-week. Evaluating schedules requires parsing wildcard asterisks (*), discrete comma lists, contiguous hyphen ranges (1-5), and periodic step intervals (*/15).
# Cron field syntax:
# minute (0-59) hour (0-23) dom (1-31) mon (1-12) dow (0-6)
# "*/15 2 * * 1-5" -> Every 15 min at 2 AM, Mon-Fri
# Gauntlet 05: Job Scheduler with Cron Expression Evaluator Every modern backend needs periodic background tasks: daily database backups at 3:00 AM, hourly invoice reconciliations, or cache flushes every 15 minutes. ⏱️📅 The standard standard for scheduling is the **Unix Cron Expression** (5 space-delimited fields): ```text ┌───────────── minute (0 - 59) │ ┌─────────── hour (0 - 23) │ │ ┌───────── day of month (1 - 31) │ │ │ ┌─────── month (1 - 12) │ │ │ │ ┌───── day of week (0 - 6, Sunday=0 or 7) │ │ │ │ │ * * * * * ``` Field expressions support: - `*`: Any value within valid field range. - `*/N`: Step operator (e.g. `*/15` in minutes = `0, 15, 30, 45`). - `A-B`: Contiguous integer range (e.g. `1-5` in DOW = Monday through Friday). - `A,B,C`: Comma-separated discrete lists. ```python # Evaluate whether a datetime matches cron specification: is_scheduled = cron_matches("*/15 3 * * *", current_dt) ``` ## Pop Quiz How does a cron step expression like `*/15` evaluate in the minute field (0-59)? - [ ] It generates values starting at 0 and incrementing by 15: `{0, 15, 30, 45}`. - [ ] It pauses job execution for 15 seconds after every completed cycle. - [ ] It evaluates only on prime minute intervals divisible by 15. - [ ] Because step operators require fractional timestamps. ## Real-World Challenge Implement `cron_matches(cron_expr: str, dt: datetime.datetime) -> bool`. - Parse all 5 standard fields: `minute`, `hour`, `day_of_month`, `month`, and `day_of_week` (`0` is Sunday or Monday depending on standard; treat Python `dt.weekday()` 0-6). - Support `*`, lists (`1,15,30`), ranges (`1-5`), and steps (`*/15` and `5-20/5`). - Return `True` if `dt` matches the cron expression. <details> <summary>Solution</summary> ```python import datetime def parse_cron_component(field: str, min_val: int, max_val: int) -> set[int]: allowed_values = set() segments = field.split(",") for segment in segments: if "/" in segment: range_part, step_str = segment.split("/") step = int(step_str) if range_part == "*": start_val, end_val = min_val, max_val elif "-" in range_part: start_str, end_str = range_part.split("-") start_val, end_val = int(start_str), int(end_str) else: start_val, end_val = int(range_part), max_val allowed_values.update(range(start_val, end_val + 1, step)) elif "-" in segment: start_str, end_str = segment.split("-") allowed_values.update(range(int(start_str), int(end_str) + 1)) elif segment == "*": allowed_values.update(range(min_val, max_val + 1)) else: allowed_values.add(int(segment)) return allowed_values def cron_matches(cron_expr: str, dt: datetime.datetime) -> bool: fields = cron_expr.strip().split() if len(fields) != 5: raise ValueError(f"Expected 5 cron fields, received {len(fields)}") minute_set = parse_cron_component(fields[0], 0, 59) hour_set = parse_cron_component(fields[1], 0, 23) dom_set = parse_cron_component(fields[2], 1, 31) month_set = parse_cron_component(fields[3], 1, 12) dow_set = parse_cron_component(fields[4], 0, 6) # In Python: Monday is 0, Sunday is 6 # In standard cron: Sunday is often 0 or 7. We check both standard Sunday mappings python_dow = dt.weekday() cron_sunday_0 = (python_dow + 1) % 7 dow_matches = (python_dow in dow_set) or (cron_sunday_0 in dow_set) return ( dt.minute in minute_set and dt.hour in hour_set and dt.day in dom_set and dt.month in month_set and dow_matches ) # Verification # Test Date: Thursday, Nov 19, 2026, 14:30:00 (Month 11, Day 19) test_dt = datetime.datetime(2026, 11, 19, 14, 30, 0) # 1. Exact match assert cron_matches("30 14 19 11 *", test_dt) is True # 2. Step match on minutes (*/15 matches 0, 15, 30, 45) assert cron_matches("*/15 * * * *", test_dt) is True # 3. Range match on hours (10-18 includes 14) assert cron_matches("30 10-18 * * *", test_dt) is True # 4. Mismatched minute assert cron_matches("0 14 * * *", test_dt) is False ``` </details>