Design a Single-Threaded Delayed Task Runner
Heaps, Sorting & SearchModel answerLast updated
Implement a priority-queue task runner that handles delayed execution without busy-waiting.
Design an execution queue engine for a single-threaded system that can schedule and run delayed callbacks.
You need to implement a class TaskRunner with the following methods:
schedule(callback, delay_ms): Registers a parameterless functioncallbackto run after at leastdelay_msmilliseconds have elapsed from the current timestamp.run(): Begins processing scheduled tasks. Tasks must execute in chronological order of their absolute target execution time. The method should block until every task in the queue has been executed, then terminate.
Requirements & Assumptions
- Tasks must execute as close as possible to their scheduled execution times in non-decreasing order of target time.
- If multiple tasks are due at the exact same millisecond, their execution order can be arbitrary.
- You may assume a system utility
get_current_time()is available, which returns the current monotonic time in milliseconds. - The execution loop inside
run()must avoid CPU-intensive spinning (busy-waiting) when waiting for the next task to become ready. - Executing callbacks might dynamically schedule additional tasks via
schedule(...).
Provided API
def get_current_time() -> int:
"""Returns the current monotonic system time in milliseconds."""
pass
Template
class TaskRunner:
def __init__(self):
pass
def schedule(self, callback: callable, delay_ms: int) -> None:
pass
def run(self) -> None:
pass
Hints
Hint 1
Convert relative delays into absolute execution timestamps upon registration.
Hint 2
What issue arises in Python when two heap elements have the same timestamp if the elements contain function objects?
Hint 3
Avoid busy-waiting loops by computing the remaining sleep duration until the next task is ready.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To implement an efficient task scheduler, we must satisfy two core requirements:
- Chronological Ordering: The task scheduled for the earliest time must always execute first.
- Efficient Waiting: When the next scheduled task is in the future, the CPU should yield/sleep for the exact remaining duration instead of continuously checking the clock (busy-waiting).
1. Data Structure Selection
A Min-Heap (Priority Queue) is ideal for this problem.
- Inserting a new task takes $O(\log N)$ time.
- Inspecting the next due task takes $O(1)$ time.
- Removing the due task takes $O(\log N)$ time.
2. Absolute vs. Relative Time
Storing relative delays directly in the queue does not work because delays tick down continuously. Instead, when schedule(callback, delay_ms) is called, we calculate the absolute target time:
$$\text{target_time} = \text{get_current_time}() + \text{delay_ms}$$
3. Resolving Tuple Comparison Conflicts in Python
Python's heapq module compares tuples element by element. If two tasks have the same target_time, Python will attempt to compare the second element: the function object callback. Since function references do not support comparison operators (<, >), this raises a TypeError.
To prevent this, we insert a monotonic sequence counter as the second tuple element: (target_time, sequence_id, callback). If target_time is equal, Python compares sequence_id, which is guaranteed to be unique and strictly increasing.
4. Execution Loop Logic
Inside run():
- Peek at the root of the min-heap to inspect the earliest task.
- Check
current_time. - If
target_time > current_time, calculate the delta(target_time - current_time)and sleep for that duration. - Once
current_time >= target_time, pop the item from the min-heap and invokecallback(). - Repeat until the min-heap is empty.
Python Implementation
import heapq
import itertools
import time
def get_current_time() -> int:
"""Returns current monotonic system time in milliseconds."""
return int(time.monotonic() * 1000)
class TaskRunner:
def __init__(self):
self._queue = []
self._seq = itertools.count()
def schedule(self, callback: callable, delay_ms: int) -> None:
if delay_ms < 0:
raise ValueError("delay_ms must be non-negative")
target_time = get_current_time() + delay_ms
task_id = next(self._seq)
heapq.heappush(self._queue, (target_time, task_id, callback))
def run(self) -> None:
while self._queue:
# Inspect the next task without popping it yet
target_time, _, callback = self._queue[0]
now = get_current_time()
if target_time > now:
# Sleep until the task is ready (convert ms to seconds)
time.sleep((target_time - now) / 1000.0)
continue
# Task is due; pop and execute
heapq.heappop(self._queue)
callback()
Complexity Analysis
-
schedule(callback, delay_ms):- Time Complexity: $O(\log N)$, where $N$ is the number of pending tasks currently in the priority queue.
- Space Complexity: $O(1)$ auxiliary space per call ($O(N)$ total to hold $N$ scheduled tasks).
-
run():- Time Complexity: $O(N \log N)$ total processing time for $N$ tasks, as each task requires one push and one pop operation.
- Space Complexity: $O(N)$ to store task references in memory.
Key Considerations & Edge Cases
delay_ms = 0: Executes on the immediate next cycle of the loop without sleeping.- Callbacks Scheduling New Tasks: If an executing callback calls
schedule(), the newly added task will be properly pushed into the min-heap. Becauserun()peeks at the heap root on every iteration, a newly inserted task with an earlier target time than existing tasks will automatically take priority on the next cycle. - Task Execution Overruns: If a callback takes longer to run than expected, subsequent tasks may become overdue. The scheduler handles this naturally: for overdue tasks,
target_time <= now, so the sleep check is bypassed and overdue tasks execute immediately back-to-back in chronological order. - Monotonic vs. Wall-Clock Time: Always use monotonic clocks (
time.monotonic()) rather than system wall-clock time (time.time()). Wall-clock time can jump forward or backward due to NTP syncs or Daylight Saving Time adjustments, breaking execution order assumptions.