KatInterview

Design a Single-Threaded Delayed Task Runner

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchheappriority-queuedesign-ds

Last 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:

  1. schedule(callback, delay_ms): Registers a parameterless function callback to run after at least delay_ms milliseconds have elapsed from the current timestamp.
  2. 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.