schedule.py

Overview

This module provides functionality to parse simplified cron-like schedule expressions and compute the next scheduled run time after a given reference datetime. It supports a minimal subset of cron syntax and enables lightweight task scheduling by converting human-readable cron expressions into structured data and performing an iterative search for the closest matching future datetime.

The core capabilities include:

This module integrates parsing and scheduling logic cohesively, serving as a foundation for time-based task execution within the system.


Classes and Functions

class CronField

A data container class representing a set of allowed integer values for a cron schedule field.

Attributes:

Usage Example:

field = CronField(values=[0, 15, 30, 45])
print(field.values)  # Output: [0, 15, 30, 45]

_expand(field: str, *, min_v: int, max_v: int) -> CronField

Expands a single cron field string into a sorted set of integer values, supporting simplified cron syntax:

Parameters:

Returns:

Example:

expand_result = _expand("1-3", min_v=0, max_v=5)
print(expand_result.values)  # Output: [1, 2, 3]

Implementation Notes:


parse(cron: str) -> tuple[CronField, CronField, CronField, CronField, CronField]

Parses a complete five-field cron expression string and returns a tuple of expanded CronField objects representing each time unit.

Parameters:

Returns:

Example:

minute, hour, dom, mon, dow = parse("0 9 * * *")
print(minute.values)  # Output: [0]
print(hour.values)    # Output: [9]
print(dom.values)     # Output: [1, 2, ..., 31] (all days of month)

Implementation Details:


next_run(cron: str, *, since: datetime | None = None) -> datetime

Calculates the next datetime that matches the given cron schedule, searching forward starting just after the provided reference time.

Parameters:

Returns:

Raises:

Example Usage:

from datetime import datetime

next_time = next_run("0 9 * * *", since=datetime(2024, 6, 1, 8, 59))
print(next_time)  # Output: 2024-06-01 09:00:00

Implementation Details:

Algorithmic Notes:


Important Implementation Details and Algorithms


Interaction with Other System Components


Visual Diagram: Class and Function Structure

classDiagram
class CronField {
+values: List[int]
}
class _expand {
+field: str
+min_v: int
+max_v: int
+returns CronField
}
class parse {
+cron: str
+returns tuple[CronField, CronField, CronField, CronField, CronField]
}
class next_run {
+cron: str
+since: datetime | None
+returns datetime
}
parse --> CronField : returns
_expand --> CronField : returns
next_run --> parse : calls
next_run --> CronField : uses

This class diagram illustrates the relationships between the key entities and functions in the module:


References to Related Topics