# 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:

1. **Reentrant Lock (RLock)**
   - Used for all operations modifying shared state
   - Allows nested acquisition by the same thread
   - Prevents deadlocks in callback scenarios

2. **Atomic State Management**
   - `run_pending()` splits into:
     1. Atomic state collection (with lock held)
     2. Unlocked callback execution
     3. Atomic state update (with lock held)

3. **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

```python
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:

1. Enable test mode to bypass encryption:
```python
scheduler.test_mode = True
```

2. 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)