Atlassian • Amazon • Datadog 60-Minute Loop

In-Memory Delayed Task Scheduler & Priority Job Queue

Task schedulers test your mastery of ordered priority queues, condition variables to prevent CPU spinning, cancellation mechanisms, and retry exponential backoffs.

Step 1: Clarifying Questions to Ask in Minutes 0–5

Clarifying Concurrency & Execution Models:

1. Execution Context:

“Should tasks execute synchronously on a single dispatcher thread or be handed off to a thread pool to avoid blocking other tasks?”

2. Tie-Breaking Policy:

“When two tasks share the exact same scheduled timestamp, should priority break ties, followed by insertion order?”

3. Task Failure & Retries:

“If an executed task throws an unhandled exception, should it retry with exponential backoff or be moved directly to a Dead Letter Queue?”

4. Task Cancellation:

“Do we need support for `cancel(taskId)` before the task triggers?”

Step 2: Core Data Structure — Min-Heap + Condition Variable

The Anti-Pattern: Busy-Spinning with `while (true) sleep(100)`

Polling the queue every 100 milliseconds is an immediate red flag in a leadership loop. It consumes idle CPU cycles and introduces up to 100ms of latency jitter.

The Senior Approach: Condition Variable with Calculated Sleep

Use a Min-Heap (PriorityQueue) ordered by `runAtTimestamp`. The background worker thread peeks at the head of the heap. If the scheduled time is in the future, it sleeps on a Condition variable with a timeout exactly equal to `runAt - now`. If a new earlier task is inserted, it notifies the condition to wake the worker immediately.

Interactive Min-Heap • Condition Variable Worker (Simulated Clock: T = 0s)
Worker Condition Variable Status:
Sleeping until T = 2s (Timeout: 2s for “P1 Incident Page”)
Schedule a New Task:
Min-Heap Order (Head is Next Due)2 queued
HeadP1 Incident Page
Due at T = 2s • Priority: 10
QUEUED
Send Weekly Digest
Due at T = 4s • Priority: 1
QUEUED
Step 3: Complete Executable Implementation
TYPESCRIPT Implementation • Full Runnable Class & Test Suite

Full 200-line code is collapsed to preserve screen focus. Click expand to inspect min-heap comparator math, thread worker logic, and unit tests.