← 返回 tesla 的题目列表Implement a Task Scheduler that Executes Tasks at Specified Times with Dynamic Inserts
类型:online_judge
Problem: Implement a Task Scheduler (dynamic inserts, execute at specified time)
Implement a runnable task scheduler that guarantees tasks are executed when their scheduled execution time is reached.
Requirements
The system maintains a set of pending tasks. Each task is associated with a scheduled time t.
Users can add new tasks at any time while the scheduler is running.
The scheduler must guarantee: each task is executed when time t is reached (or as soon as possible after), and never before t.
Provide runnable code (a demo is fine) showing that:
the scheduler runs continuously after starting
new tasks can be inserted while it is running
tasks fire at the correct times
I/O (you may define your own)
You may design your own task interface and demo, e.g.:
schedule(t, func) / schedule(delay, func)
printing logs to indicate execution (task id and actual execution timestamp)
Constraints / Edge Cases (recommended to handle)
multiple tasks can share the same scheduled time
a newly inserted task may be earlier than the current next task
avoid busy-waiting; wake up appropriately
Example test scenarios
(You may treat time units as seconds.)
Single task: insert one task at now+2s; it should run ~2s later.
Out-of-order inserts: insert a now+5s task, then a now+1s task; the now+1s task should execute first.
Same scheduled time: insert 3 tasks all at now+2s; all should run around +2s (order can be defined but consistent).
Earlier task interrupts sleep: scheduler is waiting for a now+10s task; insert a now+1s task; it should wake and run the new one first.
High-frequency inserts: insert many tasks quickly; they should still trigger in time order with no drops.
Example
Input
N/A (demo: schedule_after(2, A))
Output
~2 seconds later prints A executed ...