Design a Task Scheduling System
Difficulty: EASYCategory: LLDFrequency: 1Asked On 2025-02-13
Problem Statement
Design and implement an in-memory task scheduling system that allows registering tasks with associated executable logic (e.g., Runnable) and schedules them to run at a future point in time.
Each task:
•Has a unique ID
•Has a scheduled execution time
•Contains an executable payload (like a function or command)
The system should:
•Execute the task as close as possible to its scheduled time
•Support concurrent task executions
•Allow adding and cancelling tasks
•Be thread-safe
🎯 Functional Requirements
Implement the following core methods:
1. scheduleTask(String taskId, long executionTimeMillis, Runnable task)
•Schedules a task to be executed at the given epoch time (in ms).
•Throws error if taskId already exists.
2. cancelTask(String taskId)
•Cancels the task if it hasn't been executed yet.
3. start()
•Starts the scheduler. Tasks should begin executing in background threads.
•Only one instance of the scheduler should be active (singleton behavior).
4. stop()
•Stops the scheduler and cancels all pending tasks.
🧱 Class Design Suggestion
Task
•String taskId
•long scheduledTimeMillis
•Runnable executable
TaskScheduler
•PriorityQueue<Task> (ordered by scheduledTime)
•ConcurrentMap<String, Task> for tracking tasks
•Background worker thread (e.g., ScheduledExecutorService)
•Synchronization for thread-safety
🔐 Non-Functional Requirements
•Thread-safe: Multiple threads can add/cancel tasks safely
•Precision: Should execute tasks with millisecond-level accuracy (± small jitter)
•Efficient: Avoid polling with busy waits — use wait/notify or delay queue
•Extensible: Easy to add retry logic, recurring tasks, task result tracking
🧪 Sample Use Case
1java
2CopyEdit
3scheduleTask("email-task", now + 10_000, () -> sendEmail(...));
4scheduleTask("db-cleanup", now + 60_000, () -> runCleanupJob());
5cancelTask("email-task");
6start();🧠 Design Patterns
•Command Pattern: Runnable or custom ExecutableTask for behavior injection
•Singleton Pattern: For centralized TaskScheduler
•Producer-Consumer Pattern: Worker thread(s) picking scheduled tasks
✅ Evaluation Criteria
•Correctness: Tasks execute at correct time
•Concurrency: Safe addition/cancellation of tasks
•Clean abstraction: Testable, maintainable, extensible
•Graceful shutdown and cancellation
✨ Optional Extensions
•Support for recurring tasks (e.g., cron-like)
•Retry policies for failed tasks
•Execution logging / metrics
•Priority-based scheduling
•Task result tracking / Future<T>