44 lines
No EOL
1.4 KiB
Python
44 lines
No EOL
1.4 KiB
Python
"""Cron expression parser utility for the scheduler system."""
|
|
import croniter
|
|
from typing import Optional
|
|
from datetime import datetime, timedelta
|
|
|
|
class CronParser:
|
|
"""Parse and validate cron expressions, calculate next execution times."""
|
|
|
|
def __init__(self, cron_expression: str):
|
|
"""Initialize with a cron expression.
|
|
|
|
Args:
|
|
cron_expression: Standard cron expression string
|
|
"""
|
|
try:
|
|
self.cron = croniter.croniter(cron_expression, datetime.now())
|
|
# Force validation by checking next run time
|
|
self.next_execution()
|
|
except ValueError as e:
|
|
raise ValueError(f"Invalid cron expression: {cron_expression}") from e
|
|
|
|
def validate(self) -> bool:
|
|
"""Validate the cron expression.
|
|
|
|
Returns:
|
|
bool: True if valid, False otherwise
|
|
"""
|
|
try:
|
|
self.next_execution()
|
|
return True
|
|
except ValueError:
|
|
return False
|
|
|
|
def next_execution(self, from_time: Optional[datetime] = None) -> datetime:
|
|
"""Calculate next execution time from given time.
|
|
|
|
Args:
|
|
from_time: Reference time (defaults to now)
|
|
|
|
Returns:
|
|
datetime: Next execution time
|
|
"""
|
|
from_time = from_time or datetime.now()
|
|
return self.cron.get_next(datetime, from_time) |