SafeCron is a robust, timezone-aware Python library for parsing cron expressions, computing schedule occurrences, and handling Daylight Saving Time (DST) transitions safely. It prioritizes:
Safety: Input validation, infinite loop prevention, immutable objects, and clear error handling.
Accuracy: Wall-clock (local timezone) semantics with proper DST handling using Python's zoneinfo (stdlib since 3.9).
Standards Compliance: Supports standard 5-field Unix cron (minute hour day-of-month month day-of-week), including shorthands like @daily.
No External Dependencies: Uses only datetime, zoneinfo, and typing.
Key features:
Parse/validate cron strings.
Compute next_run, previous_run, and iterate occurrences.
Timezone support (IANA IDs, e.g., "America/New_York").
DST handling:
Spring forward (skipped times): Jumps to the next valid wall-clock time.
Fall back (duplicate times): Supports multiple runs in ambiguous periods; next_run picks the soonest future occurrence.
Edge cases: Leap years, month/year boundaries, day-of-month vs. day-of-week OR logic.
Installation (hypothetical PyPI package):
code
pip install safe-cron
API Reference
Exceptions
python
class CronParseError(ValueError): # Invalid cron syntax/range/step
class InvalidTimezoneError(ValueError): # Invalid IANA timezone
class ComputationError(RuntimeError): # Max iterations exceeded (safety)
def _advance(self, dt: datetime, direction: int = 1) -> datetime: # +1/-1
iter_count = 0
while iter_count < 10000:
iter_count += 1
y, mo, d, h, m = dt.year, dt.month, dt.day, dt.hour, dt.minute
dow = dt.weekday() + 1 # 1=Mon..7=Sun
if self.cron.matches(m, h, d, mo, dow):
return dt.replace(tzinfo=self.tz)
# Advance minute
m += direction
if not self.cron.minute.includes(m):
m = self.cron.minute.next_value(0) # Next matching min (0-59)
h += direction
# Carry over: hour → dom → month → year
if not self.cron.hour.includes(h):
h = self.cron.hour.next_value(0)
d += direction # etc.
# Month: Handle varying days (28-31), leap years via datetime.normalize
dt = dt.replace(year=y, month=mo, day=d, hour=h, minute=m, second=0, microsecond=0)
if direction > 0 and dt >= original_end: break # Bound
raise ComputationError("Max iterations exceeded")
dom/dow OR: Matches if dom or dow matches (standard cron).
DST: All ops on local naive dt, then or at end. Handles skips/duplicates naturally:
Previous Run: Symmetric, direction=-1, prev_value() instead of next_value().
Occurrences Iterator
python
dt = self.next_run(start)
while dt < end and (limit is None or count < limit):
yield dt
dt = self.next_run(dt)
This design is production-ready, extensible (e.g., add seconds, hashing for caching). Let me know if you need full code or language port (TS/JS, Go, etc.)!
ZoneInfo.localize()
astimezone
Fall back (e.g., 2024-11-03 01:00 EST/EDT): Two local 01:XX → both valid if cron matches.
Spring forward (e.g., 2024-03-10 02:00 → 03:00): Arithmetic jumps.