KatInterview

Thread-Safe Recurring Task Engine

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyheapsthreads

Last updated

Design and implement a concurrent background scheduler that manages recurring execution intervals, supports execution cancellation, and handles thread-safe termination.

Implement a thread-safe task execution system (TaskScheduler) designed to trigger recurring background jobs at regular intervals.

Your scheduler should process tasks across multiple worker threads and support live updates like task cancellation and engine shutdown without introducing race conditions or memory leaks.

Expected API

class TaskScheduler:
    def __init__(self, pool_size: int = 4):
        """Initializes the scheduler with a pool of execution threads."""
        pass

    def schedule(self, task: Callable[[], None], period_ms: int) -> int:
        """Schedules a task to run every period_ms milliseconds.
        Returns a unique integer task ID.
        Raises ValueError if period_ms < 10.
        Raises RuntimeError if the scheduler has been shut down.
        """
        pass

    def cancel(self, task_id: int) -> bool:
        """Cancels a scheduled task by ID.
        Returns True if the task was registered and active, False otherwise.
        In-flight executions should be allowed to complete.
        """
        pass

    def stop(self) -> None:
        """Signals shutdown, waits for running tasks to finish, and prevents new task submissions."""
        pass

Core Requirements

  1. Independent Execution: A long-running task must not block the dispatching or execution of other tasks.
  2. Race-Condition Safety: If cancel(task_id) is invoked while that task is executing, the current invocation should finish, but no further iterations should be queued.
  3. Graceful Termination: stop() must clean up resources, release pending jobs, block until currently executing jobs finish (unless invoked from inside a worker task), and reject new schedule() calls.
  4. Resilience: Uncaught exceptions inside user tasks must be logged/caught so they do not crash worker threads or the dispatcher loop.

Constraints

  • Minimum period period_ms is $10\text{ ms}$.
  • Time measurements must rely on monotonic clocks (time.monotonic()) to prevent system clock adjustments from disturbing schedules.

Hints

Hint 1

Use a min-heap indexed by the next target execution time to quickly identify the upcoming job, combined with a condition variable to sleep until the next execution threshold.

Hint 2

Consider rescheduling jobs only after their execution completes on a worker thread. Compare the registered ID state under lock before re-inserting into the priority queue.

Hint 3

To handle self-shutdown (a task triggering `stop()`), track thread-local context so the pool shutdown call doesn't deadlock waiting on itself.