2.1 KiB
2.1 KiB
Scheduler Documentation
Overview
The scheduler provides cron-like task scheduling capabilities with ±1 second accuracy. It supports both one-time and recurring tasks.
Key Features
- Thread-safe task registration and execution
- Support for cron expressions
- Test mode for simplified testing
- Encrypted callback storage (in production mode)
Thread Safety Implementation
The scheduler uses several techniques to ensure thread safety:
-
Reentrant Lock (RLock)
- Used for all operations modifying shared state
- Allows nested acquisition by the same thread
- Prevents deadlocks in callback scenarios
-
Atomic State Management
run_pending()splits into:- Atomic state collection (with lock held)
- Unlocked callback execution
- Atomic state update (with lock held)
-
Execution Guarantees
- Only one thread executes a given task callback
- New tasks can be registered during callback execution
- Read operations don't block write operations unnecessarily
Usage Example
from orchestrator.scheduler import Scheduler
from orchestrator.core.dispatcher import Dispatcher
dispatcher = Dispatcher()
scheduler = Scheduler(dispatcher)
def my_task():
print("Task executed!")
# Register a task that runs every minute
scheduler.register_task("minute_task", "* * * * *", my_task)
# Run pending tasks (typically in a loop)
scheduler.run_pending()
Testing Considerations
When testing scheduler behavior:
- Enable test mode to bypass encryption:
scheduler.test_mode = True
- Key test scenarios:
- Concurrent task registration
- Mixed read/write operations
- Task execution during registration
- Long-running callbacks
Performance Characteristics
- Task registration: O(1) with lock contention
- Task execution: O(n) where n is number of pending tasks
- Memory usage: Proportional to number of registered tasks
Error Handling
The scheduler handles:
- Invalid cron expressions (during registration)
- Encryption/decryption errors (in production mode)
- Callback execution errors (logged but not propagated)