# Subtask: Cron Scheduler Implementation **Parent Task**: Decomp/003 **Subtask ID**: Decomp/003-05 **Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API) ## Description Implement cron-like periodic task scheduler. Support standard cron expressions, dynamic schedule management, and distributed scheduling with leader election. ## Requirements - Parse standard cron expressions (minute, hour, day, month, weekday) - Schedule periodic tasks at defined intervals - Support multiple periodic task definitions - Dynamic add/remove/update of periodic tasks - Prevent duplicate execution in multi-worker scenarios - Track last run and next run times - Support one-shot scheduled tasks - Timezone-aware scheduling ## Technical Specifications **Cron expression parser**: ```python import re from datetime import datetime, timedelta, timezone from typing import List, Optional, Set from dataclasses import dataclass @dataclass class CronSchedule: """Parsed cron schedule.""" minute: Set[int] hour: Set[int] day: Set[int] month: Set[int] weekday: Set[int] # 0 = Monday, 6 = Sunday def matches(self, dt: datetime) -> bool: """Check if datetime matches this schedule.""" return ( dt.minute in self.minute and dt.hour in self.hour and dt.day in self.day and dt.month in self.month and dt.weekday() in self.weekday ) def next_run_time(self, after: datetime) -> datetime: """Calculate next run time after given datetime.""" # Start from next minute dt = after.replace(second=0, microsecond=0) + timedelta(minutes=1) # Search forward (max 4 years = typical cron limit) for _ in range(4 * 365 * 24 * 60): if self.matches(dt): return dt dt += timedelta(minutes=1) raise ValueError("Could not find next run time within 4 years") class CronParser: """Parse cron expressions.""" # Standard cron: minute hour day month weekday PATTERN = re.compile( r'^(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)$' ) FIELD_RANGES = { 'minute': (0, 59), 'hour': (0, 23), 'day': (1, 31), 'month': (1, 12), 'weekday': (0, 6), # 0=Monday, 6=Sunday } @classmethod def parse(cls, expression: str) -> CronSchedule: """Parse cron expression.""" m = cls.PATTERN.match(expression.strip()) if not m: raise ValueError(f"Invalid cron expression: {expression}") minute_str, hour_str, day_str, month_str, weekday_str = m.groups() return CronSchedule( minute=cls._parse_field(minute_str, 0, 59), hour=cls._parse_field(hour_str, 0, 23), day=cls._parse_field(day_str, 1, 31), month=cls._parse_field(month_str, 1, 12), weekday=cls._parse_field(weekday_str, 0, 6), ) @classmethod def _parse_field(cls, field: str, min_val: int, max_val: int) -> Set[int]: """Parse a single cron field.""" result = set() if field == '*': return set(range(min_val, max_val + 1)) # Handle comma-separated values parts = field.split(',') for part in parts: # Handle step (e.g., */5, 1-10/2) if '/' in part: base, step = part.split('/') step = int(step) if base == '*': values = range(min_val, max_val + 1) else: values = cls._parse_range(base, min_val, max_val) result.update(values[::step]) # Handle range (e.g., 1-5) elif '-' in part: result.update(cls._parse_range(part, min_val, max_val)) # Single value else: val = int(part) if not (min_val <= val <= max_val): raise ValueError(f"Value {val} out of range [{min_val}, {max_val}]") result.add(val) return result @classmethod def _parse_range(cls, range_str: str, min_val: int, max_val: int) -> List[int]: """Parse a range expression (e.g., 1-5).""" start, end = range_str.split('-') start, end = int(start), int(end) if not (min_val <= start <= max_val): raise ValueError(f"Range start {start} out of range") if not (min_val <= end <= max_val): raise ValueError(f"Range end {end} out of range") return list(range(start, end + 1)) # Common cron schedules COMMON_SCHEDULES = { "@every minute": "* * * * *", "@every 5 minutes": "*/5 * * * *", "@every 15 minutes": "*/15 * * * *", "@every hour": "0 * * * *", "@every day": "0 0 * * *", "@every week": "0 0 * * 0", "@every month": "0 0 1 * *", "@every year": "0 0 1 1 *", "@daily": "0 0 * * *", "@weekly": "0 0 * * 0", "@monthly": "0 0 1 * *", "@yearly": "0 0 1 1 *", "@annually": "0 0 1 1 *", } ``` **Periodic task scheduler**: ```python import asyncio from datetime import datetime, timezone, timedelta from typing import Dict, Optional import logging logger = logging.getLogger(__name__) class PeriodicTaskScheduler: """Scheduler for periodic/cron tasks.""" def __init__(self, db, broker, worker_name: str = "scheduler"): self.db = db self.broker = broker self.worker_name = worker_name self.running = False self.leader = False self.task = None async def start(self): """Start the scheduler.""" logger.info("Starting periodic task scheduler") self.running = True # Start leader election and main loop self.task = asyncio.create_task(self._main_loop()) async def stop(self): """Stop the scheduler.""" logger.info("Stopping periodic task scheduler") self.running = False if self.task: self.task.cancel() try: await self.task except asyncio.CancelledError: pass async def _main_loop(self): """Main scheduler loop.""" while self.running: try: # Try to become leader await self._elect_leader() if self.leader: # Check and schedule due tasks await self._check_and_schedule_tasks() # Wait before next check await asyncio.sleep(10) except asyncio.CancelledError: break except Exception as e: logger.error(f"Error in scheduler loop: {e}", exc_info=True) await asyncio.sleep(10) async def _elect_leader(self): """Participate in leader election using database advisory lock.""" async with self.db.acquire() as conn: # Try to acquire lock with 30 second timeout result = await conn.fetchval( """SELECT pg_try_advisory_lock( (SELECT hashtext('periodic_scheduler')::bigint) )""" ) if result and not self.leader: logger.info(f"{self.worker_name} became scheduler leader") self.leader = True elif not result and self.leader: logger.info(f"{self.worker_name} lost scheduler leadership") self.leader = False async def _check_and_schedule_tasks(self): """Check for due periodic tasks and schedule them.""" if not self.leader: return async with self.db.acquire() as conn: # Get active periodic tasks that are due rows = await conn.fetch( """SELECT * FROM periodic_tasks WHERE is_active = TRUE AND next_run_at <= NOW() ORDER BY next_run_at FOR UPDATE SKIP LOCKED""" ) for row in rows: await self._schedule_periodic_task(conn, dict(row)) async def _schedule_periodic_task(self, conn, task_info: dict): """Schedule a single periodic task.""" task_id = task_info["id"] name = task_info["name"] cron_expr = task_info["cron_expression"] try: # Parse cron expression cron_schedule = CronParser.parse(cron_expr) # Create the actual task from .producer import TaskProducer producer = TaskProducer(self.broker) # Generate unique task ID for this run import uuid run_id = str(uuid.uuid4()) # Enqueue the task actual_task_id = await producer.apply_async( task_func=task_info["task_name"], args=task_info.get("args", []), kwargs=task_info.get("kwargs", {}), queue=await self._get_queue_name(conn, task_info["queue_id"]) ) # Calculate next run time now = datetime.now(timezone.utc) next_run = cron_schedule.next_run_time(now) # Update periodic task await conn.execute( """UPDATE periodic_tasks SET last_run_at = NOW(), next_run_at = $1 WHERE id = $2""", next_run, task_id ) logger.info( f"Scheduled periodic task '{name}' (run: {actual_task_id}, " f"next run: {next_run.isoformat()})" ) except Exception as e: logger.error(f"Failed to schedule periodic task '{name}': {e}") async def _get_queue_name(self, conn, queue_id: int) -> str: """Get queue name from ID.""" return await conn.fetchval( "SELECT name FROM task_queues WHERE id = $1", queue_id ) async def add_periodic_task( self, name: str, task_name: str, cron_expression: str, queue: str = "default", args: list = None, kwargs: dict = None, metadata: dict = None ) -> int: """Add a new periodic task.""" # Parse cron expression to validate CronParser.parse(cron_expression) # Calculate first run time cron_schedule = CronParser.parse(cron_expression) next_run = cron_schedule.next_run_time(datetime.now(timezone.utc)) async with self.db.acquire() as conn: # Get queue ID queue_id = await conn.fetchval( "SELECT id FROM task_queues WHERE name = $1", queue ) if not queue_id: raise ValueError(f"Queue not found: {queue}") # Insert periodic task task_id = await conn.fetchval( """INSERT INTO periodic_tasks (name, task_name, cron_expression, queue_id, args, kwargs, next_run_at, is_active, metadata) VALUES ($1, $2, $3, $4, $5, $6, $7, TRUE, $8) ON CONFLICT (name) DO UPDATE SET task_name = EXCLUDED.task_name, cron_expression = EXCLUDED.cron_expression, queue_id = EXCLUDED.queue_id, args = EXCLUDED.args, kwargs = EXCLUDED.kwargs, next_run_at = EXCLUDED.next_run_at, is_active = TRUE RETURNING id""", name, task_name, cron_expression, queue_id, args or [], kwargs or {}, next_run, metadata or {} ) logger.info(f"Added periodic task '{name}' with schedule '{cron_expression}'") return task_id async def remove_periodic_task(self, name: str) -> bool: """Remove a periodic task.""" async with self.db.acquire() as conn: result = await conn.execute( "DELETE FROM periodic_tasks WHERE name = $1", name ) return result != "DELETE 0" async def disable_periodic_task(self, name: str) -> bool: """Disable a periodic task without removing it.""" async with self.db.acquire() as conn: result = await conn.execute( "UPDATE periodic_tasks SET is_active = FALSE WHERE name = $1", name ) return result != "UPDATE 0" async def enable_periodic_task(self, name: str) -> bool: """Enable a disabled periodic task.""" async with self.db.acquire() as conn: # Recalculate next run time task_info = await conn.fetchrow( "SELECT * FROM periodic_tasks WHERE name = $1", name ) if not task_info: return False cron_schedule = CronParser.parse(task_info["cron_expression"]) next_run = cron_schedule.next_run_time(datetime.now(timezone.utc)) await conn.execute( """UPDATE periodic_tasks SET is_active = TRUE, next_run_at = $1 WHERE name = $2""", next_run, name ) return True async def list_periodic_tasks(self) -> list: """List all periodic tasks.""" async with self.db.acquire() as conn: rows = await conn.fetch( """SELECT name, task_name, cron_expression, is_active, last_run_at, next_run_at FROM periodic_tasks ORDER BY name""" ) return [dict(row) for row in rows] ``` **Decorator for periodic tasks**: ```python def periodic( cron_expression: str, name: str = None, queue: str = "default" ): """ Decorator to register a function as a periodic task. Usage: @periodic("0 0 * * *", name="daily_cleanup") def cleanup_old_data(): ... """ def decorator(func): task_name = f"{func.__module__}.{func.__name__}" periodic_name = name or task_name # Register as periodic task PERIODIC_TASK_REGISTRY[periodic_name] = { "task_name": task_name, "cron_expression": cron_expression, "queue": queue, "func": func } return func return decorator # Global periodic task registry PERIODIC_TASK_REGISTRY = {} ``` ## Acceptance Criteria - [ ] Standard cron expressions are parsed correctly - [ ] Periodic tasks execute at scheduled times - [ ] Only one scheduler instance schedules tasks (leader election) - [ ] Next run times are calculated accurately - [ ] Tasks can be added/removed/enabled/disabled dynamically - [ ] Timezone handling works correctly - [ ] Common schedules (@daily, @hourly) are supported ## Notes **Trade-offs**: - Database lock vs external coordinator: Database lock simpler - Check interval: 10 seconds balances accuracy vs load **Performance**: - Use SKIP LOCKED for concurrent scheduler instances - Batch task scheduling to reduce transactions **Alternatives considered**: - Celery beat: Similar approach adopted - APScheduler integration: Rejected, built-in is sufficient