Delayed Runnable Scheduler
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-02-22
Problem Statement
Design and implement a multithreaded scheduler that can schedule and execute tasks (Runnable/Callable) after a specified delay.
Design and implement a multithreaded Delayed Runnable Scheduler that accepts tasks with a specified delay, executes them once the delay expires, supports cancellation and graceful shutdown, and works efficiently in a concurrent environment.
This should work like a simplified version of Java’s ScheduledExecutorService.
🔶 Requirements
1.<span></span>Task Scheduling
2.<span></span>The scheduler should accept tasks (Runnable or Callable) along with a delay (in milliseconds/seconds).
3.<span></span>After the delay elapses, the task must be executed.
4.<span></span>Concurrency
5.<span></span>Multiple tasks can be scheduled concurrently.
6.<span></span>Tasks may run in parallel if their delays expire at similar times.
7.<span></span>Thread Safety
8.<span></span>The scheduler should work correctly in a multithreaded environment where multiple threads submit tasks simultaneously.
9.<span></span>Resource Management
10.<span></span>Use a thread pool or worker threads to execute scheduled tasks.
11.<span></span>Ensure tasks don’t block the scheduler’s core thread (which tracks time).
12.<span></span>Cancellation
13.<span></span>Support cancellation of scheduled tasks before they are executed.
14.<span></span>Shutdown
15.<span></span>Support graceful shutdown:
16.<span></span>Stop accepting new tasks.
17.<span></span>Allow already scheduled tasks to complete.
18.<span></span>Error Handling
19.<span></span>Exceptions inside tasks should not crash the scheduler.
20.<span></span>Proper logging of failures.
🔶 Constraints
1.<span></span>Scheduler must support at least 10,000 scheduled tasks concurrently.
2.<span></span>Delay precision should be in milliseconds.
3.<span></span>Should efficiently handle tasks with very short delays and very long delays.
🔶 Example Use Cases
1.<span></span>Run a timeout handler that cancels a database query if it runs for more than 5 seconds.
2.<span></span>Schedule a retry task (e.g., API call retry after 2 seconds).
3.<span></span>Implement a background job system (e.g., clear cache every 10 seconds).
🔶 Expectations
Your design should:
1.<span></span>Provide a schedule(Runnable task, long delay) method.
2.<span></span>Optionally provide schedule(Callable<T> task, long delay) with a Future<T>.
3.<span></span>Ensure efficient scheduling (e.g., use a min-heap/PriorityQueue based on execution time).
4.<span></span>Clearly specify synchronization (locks, condition variables, or concurrent data structures).
5.<span></span>Demonstrate with a driver program: