Delayed Task Scheduler

Hard
ConcurrencyPriority QueueDelayed QueueThread PoolScheduledExecutorServiceTimer Wheel

Problem Statement

Design a thread-safe delayed task scheduler that executes tasks at specified times in the future. Tasks can be one-time (execute once at a specified delay) or recurring (execute at fixed intervals). The scheduler must be efficient for a large number of pending tasks.

class TaskScheduler {
    public TaskScheduler(int threadPoolSize) {}
    // Schedule task to run after `delayMs` milliseconds
    public ScheduledTask schedule(Runnable task, long delayMs) {}
    // Schedule task to run repeatedly at `periodMs` intervals
    public ScheduledTask scheduleAtFixedRate(Runnable task, long initialDelayMs, long periodMs) {}
    // Schedule with fixed delay between end of one run and start of next
    public ScheduledTask scheduleWithFixedDelay(Runnable task, long initialDelayMs, long delayMs) {}
    public void cancel(ScheduledTask task) {}
    public void shutdown() {}
}

interface ScheduledTask {
    boolean cancel();
    boolean isCancelled();
    long getNextExecutionTime();
}

Key Entities

  • DelayQueue<ScheduledTaskEntry>: Priority queue ordering tasks by next execution time.
  • Worker thread: Polls DelayQueue; when a task becomes ready (delay expired), submits to thread pool.
  • ExecutorService: Runs the actual task logic in parallel.
  • CancellationFlag: AtomicBoolean per task; worker checks before executing.

Requirements

  1. Tasks execute no earlier than their scheduled time (bounded latency up to scheduling resolution).
  2. Recurring tasks re-enqueue themselves after each execution.
  3. Cancelled tasks are never executed (even if already in the queue).
  4. The scheduler thread efficiently sleeps until the next task is due (no polling).
  5. Thread pool handles concurrent execution of multiple ready tasks.

Asked at: Google, Amazon, Microsoft, Uber, Netflix, Quartz, LinkedIn

!Constraints

- Up to 1,000,000 pending scheduled tasks. - Scheduling resolution: 1 millisecond. - Thread pool size: 1–100 threads. - Recurring task period minimum: 10 milliseconds. - cancel() on an already-executing task must not interrupt it (just prevent future recurrences).
Output

Run or submit your code to see output here.