Files
sdb2-backend/SCHEDULER_EXAMPLE.md
JSC 03abed6d39 Add comprehensive tests for scheduled task repository, scheduler service, and task handlers
- Implemented tests for ScheduledTaskRepository covering task creation, retrieval, filtering, and status updates.
- Developed tests for SchedulerService including task creation, cancellation, user task retrieval, and maintenance jobs.
- Created tests for TaskHandlerRegistry to validate task execution for various types, including credit recharge and sound playback.
- Ensured proper error handling and edge cases in task execution scenarios.
- Added fixtures and mocks to facilitate isolated testing of services and repositories.
2025-08-28 22:37:43 +02:00

6.4 KiB

Enhanced Scheduler System - Usage Examples

This document demonstrates how to use the new comprehensive scheduled task system.

Features Overview

Task Types

  • Credit Recharge: Automatic or scheduled credit replenishment
  • Play Sound: Schedule individual sound playback
  • Play Playlist: Schedule playlist playback with modes

🌍 Timezone Support

  • Full timezone support with automatic UTC conversion
  • Specify any IANA timezone (e.g., "America/New_York", "Europe/Paris")

🔄 Scheduling Options

  • One-shot: Execute once at specific date/time
  • Recurring: Hourly, daily, weekly, monthly, yearly intervals
  • Cron: Custom cron expressions for complex scheduling

API Usage Examples

Create a One-Shot Task

# Schedule a sound to play in 2 hours
curl -X POST "http://localhost:8000/api/v1/scheduler/tasks" \
  -H "Content-Type: application/json" \
  -H "Cookie: access_token=YOUR_JWT_TOKEN" \
  -d '{
    "name": "Play Morning Alarm",
    "task_type": "play_sound", 
    "scheduled_at": "2024-01-01T10:00:00",
    "timezone": "America/New_York",
    "parameters": {
      "sound_id": "sound-uuid-here"
    }
  }'

Create a Recurring Task

# Daily credit recharge at midnight UTC
curl -X POST "http://localhost:8000/api/v1/scheduler/admin/system-tasks" \
  -H "Content-Type: application/json" \
  -H "Cookie: access_token=ADMIN_JWT_TOKEN" \
  -d '{
    "name": "Daily Credit Recharge",
    "task_type": "credit_recharge",
    "scheduled_at": "2024-01-01T00:00:00",
    "timezone": "UTC",
    "recurrence_type": "daily",
    "parameters": {}
  }'

Create a Cron-Based Task

# Play playlist every weekday at 9 AM
curl -X POST "http://localhost:8000/api/v1/scheduler/tasks" \
  -H "Content-Type: application/json" \
  -H "Cookie: access_token=YOUR_JWT_TOKEN" \
  -d '{
    "name": "Workday Playlist",
    "task_type": "play_playlist",
    "scheduled_at": "2024-01-01T09:00:00",
    "timezone": "America/New_York", 
    "recurrence_type": "cron",
    "cron_expression": "0 9 * * 1-5",
    "parameters": {
      "playlist_id": "playlist-uuid-here",
      "play_mode": "loop",
      "shuffle": true
    }
  }'

Python Service Usage

from datetime import datetime, timedelta
from app.services.scheduler import SchedulerService
from app.models.scheduled_task import TaskType, RecurrenceType

# Initialize scheduler service
scheduler_service = SchedulerService(db_session_factory, player_service)

# Create a one-shot task
task = await scheduler_service.create_task(
    name="Test Sound",
    task_type=TaskType.PLAY_SOUND,
    scheduled_at=datetime.utcnow() + timedelta(hours=2),
    timezone="America/New_York",
    parameters={"sound_id": "sound-uuid-here"},
    user_id=user.id
)

# Create a recurring task
recurring_task = await scheduler_service.create_task(
    name="Weekly Playlist",
    task_type=TaskType.PLAY_PLAYLIST,
    scheduled_at=datetime.utcnow() + timedelta(days=1),
    recurrence_type=RecurrenceType.WEEKLY,
    recurrence_count=10,  # Run 10 times then stop
    parameters={
        "playlist_id": "playlist-uuid",
        "play_mode": "continuous",
        "shuffle": False
    },
    user_id=user.id
)

# Cancel a task
success = await scheduler_service.cancel_task(task.id)

# Get user's tasks
user_tasks = await scheduler_service.get_user_tasks(
    user_id=user.id,
    status=TaskStatus.PENDING,
    limit=20
)

Task Parameters

Credit Recharge Parameters

{
  "user_id": "uuid-string-or-null"  // null for all users (system task)
}

Play Sound Parameters

{
  "sound_id": "uuid-string"  // Required: sound to play
}

Play Playlist Parameters

{
  "playlist_id": "uuid-string",        // Required: playlist to play
  "play_mode": "continuous",           // Optional: continuous, loop, loop_one, random, single
  "shuffle": false                     // Optional: shuffle playlist
}

Recurrence Types

Type Description Example
none One-shot execution Single alarm
hourly Every hour Hourly reminders
daily Every day Daily credit recharge
weekly Every week Weekly reports
monthly Every month Monthly maintenance
yearly Every year Annual renewals
cron Custom cron expression Complex schedules

Cron Expression Examples

Expression Description
0 9 * * * Daily at 9 AM
0 9 * * 1-5 Weekdays at 9 AM
30 14 1 * * 1st of month at 2:30 PM
0 0 * * 0 Every Sunday at midnight
*/15 * * * * Every 15 minutes

System Tasks vs User Tasks

System Tasks

  • Created by administrators
  • No user association (user_id is null)
  • Typically for maintenance operations
  • Accessible via admin endpoints

User Tasks

  • Created by regular users
  • Associated with specific user
  • User can only manage their own tasks
  • Accessible via regular user endpoints

Error Handling

The system provides comprehensive error handling:

  • Invalid Parameters: Validation errors for missing or invalid task parameters
  • Scheduling Conflicts: Prevention of resource conflicts
  • Timezone Errors: Invalid timezone specifications handled gracefully
  • Execution Failures: Failed tasks marked with error messages and retry logic
  • Expired Tasks: Automatic cleanup of expired tasks

Monitoring and Management

Get Task Status

curl "http://localhost:8000/api/v1/scheduler/tasks/{task-id}" \
  -H "Cookie: access_token=YOUR_JWT_TOKEN"

List User Tasks

curl "http://localhost:8000/api/v1/scheduler/tasks?status=pending&limit=10" \
  -H "Cookie: access_token=YOUR_JWT_TOKEN"

Admin: View All Tasks

curl "http://localhost:8000/api/v1/scheduler/admin/tasks?limit=50" \
  -H "Cookie: access_token=ADMIN_JWT_TOKEN"

Cancel Task

curl -X DELETE "http://localhost:8000/api/v1/scheduler/tasks/{task-id}" \
  -H "Cookie: access_token=YOUR_JWT_TOKEN"

Migration from Old Scheduler

The new system automatically:

  1. Creates system tasks: Daily credit recharge task created on startup
  2. Maintains compatibility: Existing credit recharge functionality preserved
  3. Enhances functionality: Adds user tasks and new task types
  4. Improves reliability: Better error handling and timezone support

The old scheduler is completely replaced - no migration needed for existing functionality.