Design a Task Scheduler

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-02-20

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:


•Schedule tasks (Runnable/Callable functions) to run:
•After a certain delay.
•At a fixed rate (e.g., every 10 seconds).
•At a specific timestamp.
•Manage concurrent task execution.
•Handle task cancellation and rescheduling.
•Ensure accurate timing and thread-safe execution.


✅ Functional Requirements


1. Task Scheduling


•Ability to schedule a task to execute:
•Once after a delay → e.g., “Run this task after 10 seconds.”
•Periodically → e.g., “Run this every 5 minutes.”
•At a fixed time → e.g., “Run this at 8:00 AM every day.”
•Each task has:
•Unique ID
•Runnable/Callable function
•Scheduled time or interval
•Status (SCHEDULED, RUNNING, COMPLETED, CANCELLED)


2. Task Execution


•Scheduler should:
•Pick the next eligible task based on time.
•Execute it using worker threads.
•Reschedule periodic tasks.
•Should not block other tasks — use thread pool or background threads.


3. Task Management


•Support:
•schedule(task, delay)
•scheduleAtFixedRate(task, initialDelay, interval)
•cancel(taskId)
•reschedule(taskId, newTime/interval)
•Provide status queries for tasks (e.g., get all running tasks).


4. Concurrency & Timing


•Multiple tasks can run concurrently.
•Scheduler ensures precise execution time (within milliseconds).
•Thread-safe operations for task registration and execution.


5. Error Handling


•If a task throws an exception, it should:
•Log error details.
•Optionally retry (based on configuration).
•Failed tasks should not affect other tasks.


⚙️ Non-Functional Requirements


•Accurate: Tasks must run close to scheduled time.
•Thread-safe: No race conditions or deadlocks.
•Scalable: Should handle hundreds of concurrent scheduled tasks.
•Extensible: Easy to add retry logic or persistence.
•Lightweight: Efficient CPU utilization.


🧱 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.User Schedules Tasks
1 2Task 1 → Run after 5 sec 3Task 2 → Run every 10 sec
1.Scheduler Thread

Maintains 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


•Command Pattern → Tasks encapsulate executable behavior.
•Strategy Pattern → Different scheduling strategies (fixed rate, delay, etc.).
•Observer Pattern → Notify listeners on task completion/failure.
•Singleton Pattern → Global TaskScheduler instance (optional).


⚡ Possible Extensions


•Add persistence for scheduled tasks (in DB).
•Add retry and exponential backoff logic.
•Add distributed scheduling (multi-node coordination).
•Add metrics and logging (average delay, success rate).
•Add priority-based execution.


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


•Allows one-time and recurring task scheduling.
•Executes tasks concurrently and on time.
•Manages task states and cancellations.
•Is modular, thread-safe, and extensible.


Solution

Comments