Designing a Task Scheduler

Difficulty: Intermediate Patterns: Strategy, Observer, Thread Pool Asked at: Google, Amazon, Microsoft, Uber

💡 Design pattern = a named, reusable solution to a problem that keeps recurring in object-oriented code, which is why “use Strategy here” conveys a whole shape of code in one word. New to this vocabulary? Start with the machine coding round primer.


Functional Requirements

  1. Schedule tasks at specific times - submit a task to run at a given future timestamp
  2. Recurring tasks - support tasks that repeat at fixed intervals (every N seconds/minutes)
  3. Priority queue - higher priority tasks execute first when multiple tasks are due
  4. Cancel tasks - cancel a scheduled or recurring task by its ID before execution
  5. Thread pool execution - execute tasks concurrently using a configurable thread pool
  6. Delayed execution - schedule a task to run after a specified delay from now

Non-Functional Requirements

  1. Thread-safety - concurrent scheduling/cancelling must not corrupt internal state
    💡 Thread-safety = the code still behaves correctly when several threads run it at the same instant. Here the dispatcher thread is reading the queue while client threads are adding to it.
  2. Efficient polling - use min-heap so next task is always O(1) peek, O(log n) extract
    💡 O(1) = constant time, O(log n) = cost grows with the logarithm of the queue size. Peeking at the next due task is free; removing it costs a handful of comparisons even with a million tasks queued.
  3. Graceful shutdown - complete in-progress tasks, discard pending ones on shutdown
    💡 Graceful shutdown = stop accepting new work, let what is already running finish, then exit, instead of killing threads mid-task and leaving half-done work behind.

Core Entities

Entity Description
Task Encapsulates a unit of work with an ID, priority, and execution logic
TaskType Enum: ONE_TIME, RECURRING, DELAYED
Priority Enum: LOW, MEDIUM, HIGH, CRITICAL
ScheduledTask Wraps a Task with scheduling metadata (next run time, interval)
TaskScheduler Central orchestrator - schedules, cancels, dispatches tasks
ExecutionStrategy Interface for how tasks are executed (thread pool, single thread)
ThreadPoolExecutor Executes tasks using a fixed thread pool
TaskObserver Interface notified on task lifecycle events (started, completed, failed)

💡 Enum = a fixed, named set of constant values (ONE_TIME, RECURRING, DELAYED), so the compiler rejects a typo that a plain string would happily accept.

💡 Interface = a list of method signatures with no bodies. ExecutionStrategy is one, which lets the scheduler call execute(task) without knowing whether a thread pool, a single thread or something async is behind it.


Class Diagram

classDiagram
    class Priority {
        <<enumeration>>
        LOW
        MEDIUM
        HIGH
        CRITICAL
    }

    class TaskType {
        <<enumeration>>
        ONE_TIME
        RECURRING
        DELAYED
    }

    class Task {
        -String id
        -String name
        -Priority priority
        -Runnable action
        +execute()
        +getId() String
        +getPriority() Priority
    }

    class ScheduledTask {
        -Task task
        -long nextRunTimeMs
        -long intervalMs
        -TaskType type
        -boolean cancelled
        +cancel()
        +isCancelled() boolean
        +getNextRunTime() long
        +reschedule()
    }

    class ExecutionStrategy {
        <<interface>>
        +execute(Task task)
        +shutdown()
    }

    class ThreadPoolStrategy {
        -ExecutorService pool
        +execute(Task task)
        +shutdown()
    }

    class TaskObserver {
        <<interface>>
        +onTaskStarted(Task task)
        +onTaskCompleted(Task task)
        +onTaskFailed(Task task, Exception e)
        +onTaskCancelled(Task task)
    }

    class TaskScheduler {
        -PriorityQueue~ScheduledTask~ taskQueue
        -Map~String, ScheduledTask~ taskRegistry
        -ExecutionStrategy executor
        -List~TaskObserver~ observers
        -boolean running
        +schedule(Task, long delayMs) String
        +scheduleAt(Task, long timestampMs) String
        +scheduleRecurring(Task, long intervalMs) String
        +cancel(String taskId) boolean
        +start()
        +shutdown()
    }

    TaskScheduler --> ExecutionStrategy
    TaskScheduler --> ScheduledTask
    TaskScheduler --> TaskObserver
    ScheduledTask --> Task
    Task --> Priority
    ScheduledTask --> TaskType
    ExecutionStrategy <|.. ThreadPoolStrategy

💡 In a UML class diagram the solid arrow --> means “holds a reference to”, the dashed arrow <|.. means “implements this interface”, - marks a private field and + a public method.

Key classes:

  • Task - the unit of work. It carries an ID, a priority and the action to run, and nothing about when it runs.
  • ScheduledTask - the scheduling wrapper around a Task. It owns the timing facts (next run time, repeat interval, type) and the cancelled flag, which is why cancelling never has to touch the Task itself.
  • TaskScheduler - the orchestrator. It owns the queue of pending work, the registry used to cancel by ID, the observer list and the dispatcher thread that decides what is due.
  • ExecutionStrategy - the swappable answer to “how do we actually run this?”. The scheduler depends on this interface, not on threads.
  • ThreadPoolStrategy - the one implementation shipped here; it hands tasks to a fixed-size pool so concurrency stays bounded.
  • TaskObserver - the notification hook. Logging, metrics and alerting subscribe here instead of being wired into the scheduler.

Design Patterns

Pattern Where Why
Strategy ExecutionStrategy interface with ThreadPoolStrategy Swap execution model (single-thread, thread pool, async) without changing scheduler logic
Observer TaskObserver notified on task start/complete/fail/cancel Decouple logging, metrics, alerting from core scheduling
Thread Pool ThreadPoolStrategy wraps a fixed-size executor Bound concurrency, reuse threads, prevent resource exhaustion
Command Task encapsulates action as an object Tasks are first-class objects that can be queued, cancelled, rescheduled

💡 Strategy pattern = put each algorithm behind a shared interface so the surrounding code can swap it at runtime. Switching from a thread pool to single-threaded execution is one new class and one constructor argument.

💡 Observer pattern = interested objects subscribe to another object’s events and get called back when something happens, so adding metrics never means editing the scheduler.

💡 Thread pool = a fixed set of worker threads that pull work from a queue. Reusing N threads avoids the cost of creating one per task and caps how much runs at once.

💡 Command pattern = wrap “the work to do” in an object instead of calling it straight away, which is precisely what lets a task be queued, delayed, cancelled or rescheduled.


Data Structures

Component Structure Why
Task queue PriorityQueue<ScheduledTask> (min-heap by next run time + priority) O(1) peek next task, O(log n) insert/extract
Task registry ConcurrentHashMap<String, ScheduledTask> O(1) lookup for cancel by ID
Observers CopyOnWriteArrayList<TaskObserver> Thread-safe iteration during notification
Thread pool FixedThreadPool(n) Bounded concurrency for task execution

💡 Min-heap = a tree kept in an array where every parent sorts before its children, so the smallest element (here the earliest due task) is always at index 0. That is why peeking is free and only removal has to re-shuffle.