← 返回 tesla 的题目列表Task Scheduler with Timed Execution and Dynamic Insertion
类型:qbank
Infra coding screen: implement a task scheduler that runs each task at its designated time, while allowing new tasks to be added at any point. The code must actually run.
Requirements
Implement a task scheduler that executes tasks at a specified time.
Support adding new tasks at any moment, including after the scheduler has started running.
Each task carries a target execution time; the scheduler must fire it at (or as close as possible to) that time.
The solution must be runnable, not just a sketch.
Notes
A min-heap keyed by execution time is the natural backbone: the scheduler always waits until the earliest scheduled task is due, then pops and runs it.
The hard part is dynamic insertion while waiting: a newly added task with an earlier time than the current head must be able to preempt the wait. Clarify whether a single worker thread with a condition variable, a timed wait that re-checks on insertion, or an event loop is expected.
Clarify single-threaded vs multi-threaded execution, whether tasks run sequentially or concurrently, and whether late tasks should still fire or be dropped.
Discuss thread-safety of the shared queue (lock around heap push/pop) and how to wake the worker when a sooner task arrives (notify on the condition variable).
Preparation
Implement a single-worker scheduler over a heap with a condition variable: worker computes the wait until the head's due time, and add_task pushes then notifies to recompute the wait.
Test adding a task that is due immediately, adding a sooner task while the worker is waiting on a later one, and many tasks due at the same timestamp.
Be ready to extend to a thread pool so multiple due tasks can run concurrently.