Thread-Safe Recurring Task Engine
Data Structure DesignModel answerLast 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
- Independent Execution: A long-running task must not block the dispatching or execution of other tasks.
- 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. - 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 newschedule()calls. - 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_msis $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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
Designing a concurrent recurring scheduler requires decoupling task dispatching from task execution, while maintaining strict state synchronization across thread boundaries.
Core Design Elements
- Priority Queue (Min-Heap): Tracks scheduled jobs ordered by
next_run_timestamp. The min-heap allows $O(1)$ access to the next immediate due task and $O(\log N)$ extraction. - Task State Registry: A dictionary mapping
task_idto its metadata (closure, interval, target run time). This provides $O(1)$ cancellation checking and serves as the single source of truth for job validity. - Dispatcher & Worker Execution Pool: A dedicated background dispatcher thread waits on a
threading.Conditionuntil the earliest heap entry is ready. It pops the job and submits the work payload to aThreadPoolExecutor. - Completion-Based Rescheduling Strategy: A task is removed from the priority queue before submission to worker threads. Upon completion, the worker thread attempts to re-enqueue the job for its next interval. Re-enqueuing requires validating that the task is still registered in the dictionary under lock.
Synchronizing Cancellation and Rescheduling
Handling cancellation while a job is running requires serializing state checks. By performing the cancel() removal and the post-run re-enqueue inside the same monitor lock:
- If
cancel()executes first, it removes the entry from the registry dictionary. When the worker finishes, its check against the registry fails, preventing re-insertion into the min-heap. - If the worker re-enqueues first, a subsequent
cancel()will remove the task ID from the dictionary. The next time the dispatcher pops that job ID from the heap, it checks the dictionary, sees missing metadata, and discards it lazily.
Python 3 Implementation
import heapq
import itertools
import logging
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Callable, Optional, Tuple
logger = logging.getLogger(__name__)
@dataclass
class _TaskMetadata:
fn: Callable[[], None]
period: float # seconds
next_run: float # monotonic time timestamp
class TaskScheduler:
def __init__(self, pool_size: int = 4):
self._lock = threading.Lock()
self._cond = threading.Condition(self._lock)
# Priority queue storing tuples: (next_run_timestamp, task_id)
self._heap: list[Tuple[float, int]] = []
self._tasks: dict[int, _TaskMetadata] = {}
self._id_gen = itertools.count(1)
self._is_shutdown = False
self._thread_local = threading.local()
self._pool = ThreadPoolExecutor(max_workers=pool_size)
self._dispatcher = threading.Thread(target=self._dispatch_loop, daemon=True)
self._dispatcher.start()
def schedule(self, task: Callable[[], None], period_ms: int) -> int:
if period_ms < 10:
raise ValueError("Execution period must be at least 10 ms.")
period_sec = period_ms / 1000.0
with self._cond:
if self._is_shutdown:
raise RuntimeError("Cannot schedule tasks on a shutdown scheduler.")
task_id = next(self._id_gen)
first_run = time.monotonic() + period_sec
meta = _TaskMetadata(fn=task, period=period_sec, next_run=first_run)
self._tasks[task_id] = meta
heapq.heappush(self._heap, (first_run, task_id))
# Wake dispatcher in case this new task is due earlier than current head
self._cond.notify()
return task_id
def cancel(self, task_id: int) -> bool:
with self._cond:
return self._tasks.pop(task_id, None) is not None
def stop(self) -> None:
with self._cond:
if self._is_shutdown:
return
self._is_shutdown = True
self._tasks.clear()
self._heap.clear()
self._cond.notify_all()
# Join dispatcher thread
self._dispatcher.join()
# Prevent deadlock if stop() is called from inside a worker task
is_worker = getattr(self._thread_local, "is_worker", False)
self._pool.shutdown(wait=not is_worker)
def _get_next_due_task(self) -> Optional[Tuple[int, _TaskMetadata]]:
"""Blocks until a job is ready for execution, returning None on shutdown."""
with self._cond:
while not self._is_shutdown:
if not self._heap:
self._cond.wait()
continue
due_time, task_id = self._heap[0]
now = time.monotonic()
time_remaining = due_time - now
if time_remaining > 0:
self._cond.wait(timeout=time_remaining)
continue
heapq.heappop(self._heap)
meta = self._tasks.get(task_id)
# If metadata exists, task was not cancelled while waiting in queue
if meta is not None:
return task_id, meta
return None
def _dispatch_loop(self) -> None:
while True:
item = self._get_next_due_task()
if item is None:
break
task_id, meta = item
self._pool.submit(self._execute_wrapper, task_id, meta)
def _execute_wrapper(self, task_id: int, meta: _TaskMetadata) -> None:
self._thread_local.is_worker = True
try:
meta.fn()
except Exception:
logger.exception("Exception occurred during task execution: %s", task_id)
with self._cond:
if self._is_shutdown or task_id not in self._tasks:
return
# Compute next run time aligned relative to monotonic clock
meta.next_run = time.monotonic() + meta.period
heapq.heappush(self._heap, (meta.next_run, task_id))
self._cond.notify()
Complexity Analysis
-
Time Complexity:
schedule(): $\mathcal{O}(\log N)$ to push to the min-heap.cancel(): $\mathcal{O}(1)$ hash map deletion. The corresponding heap element is removed lazily in $\mathcal{O}(\log N)$ time when it reaches the top.- Dispatch Iteration: $\mathcal{O}(\log N)$ per task run (heap pop and re-enqueue).
stop(): $\mathcal{O}(N)$ to clear tracking structures, plus the time required for active pool threads to complete.
-
Space Complexity:
- $\mathcal{O}(N)$ space storing active job references in both the hash table and min-heap, where $N$ is the count of registered active schedules.