Design a Task Scheduler
Problem Statement
Design the Low-Level Design (LLD) for a Task Scheduler System, similar to how cron jobs, Celery beat, or OS-level schedulers (like Windows Task Scheduler) work.
The system should allow tasks to be scheduled for execution — once, at fixed intervals, or after a specific delay.
It should manage task execution, queuing, and thread safety, ensuring tasks run at the correct time even when multiple are scheduled simultaneously.
🎯 Goal
Design a Task Scheduler that can:
✅ Functional Requirements
1. Task Scheduling
2. Task Execution
3. Task Management
4. Concurrency & Timing
5. Error Handling
⚙️ Non-Functional Requirements
🧱 Key Classes to Design
ClassResponsibility
Task
Represents a unit of work to be executed.
ScheduledTask
Wraps Task with timing info (start time, interval, etc.).
TaskScheduler
Core class that manages task scheduling, timing, and execution.
TaskExecutor
Uses thread pool to run tasks concurrently.
TaskStore
Keeps all active, completed, and cancelled tasks.
Clock / TimerService
Provides time tracking and sleep/wakeup logic.
TaskStatus
Enum representing task state (SCHEDULED, RUNNING, COMPLETED, CANCELLED).
🧩 Suggested Class Design
1
2Task
3 ├── String id
4 ├── Runnable command
5 ├── TaskStatus status
6
7ScheduledTask extends Task
8 ├── long scheduledTime
9 ├── long interval (optional)
10 ├── boolean isRecurring
11
12TaskScheduler
13 ├── PriorityQueue<ScheduledTask> taskQueue (sorted by scheduledTime)
14 ├── ThreadPoolExecutor executor
15 ├── schedule(Task task, delay)
16 ├── scheduleAtFixedRate(Task task, initialDelay, interval)
17 ├── cancel(String taskId)
18 ├── runSchedulerLoop()
19
20TaskExecutor
21 ├── execute(Task task)
22
23TaskStatus (Enum)
24 ├── SCHEDULED
25 ├── RUNNING
26 ├── COMPLETED
27 ├── CANCELLED
28 ├── FAILED🔄 Flow Example
1
2Task 1 → Run after 5 sec
3Task 2 → Run every 10 secMaintains a priority queue (by next execution time).
Sleeps until the next task’s execution time.
Dispatches due task to the thread pool.
3. Task Execution
Thread pool runs the task.
Marks it as COMPLETED or FAILED.
If recurring, re-inserts it into the queue with updated next time.
4. User Cancels Task
Remove from queue.
Update status to CANCELLED.
🧠 Design Patterns
⚡ Possible Extensions
🧾 Example Scenario
1
2TaskScheduler scheduler = new TaskScheduler();
3
4scheduler.schedule(() -> System.out.println("Run after 5 sec"), 5000);
5
6scheduler.scheduleAtFixedRate(() -> System.out.println("Run every 10 sec"), 2000, 10000);Output:
1
2(After 5s) Run after 5 sec
3(Every 10s) Run every 10 sec✅ Final Summary:
Design a Task Scheduler (LLD) that: