Implement a single-thread task scheduler API
Company: Applied
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Design and implement a simple task scheduler for a **single CPU, single thread** environment.
You need to support scheduling callbacks (tasks) using the following APIs:
- `scheduleOnce(task, runAtTime)`
- runs `task` exactly once at the specified absolute time.
- `scheduleWithDelay(task, delay)`
- runs `task` exactly once after the specified delay from “now”.
- `schedulePeriodic(task, initialDelay, period)`
- runs `task` first after `initialDelay`, then repeatedly every `period`.
### Requirements
- Only one task runs at a time (no parallelism).
- If multiple tasks are due at the same time, execute them in a deterministic order (define one).
- Define behavior if a periodic task’s next run time is missed because execution took too long.
- Include how the scheduler waits/sleeps and wakes up to run the next task.
### Deliverable
Describe the data structures and implement the scheduler logic.
Quick Answer: This question evaluates understanding of task scheduling, timing semantics, deterministic ordering, single-thread concurrency control, and data structure choices for managing timed and periodic callbacks.
Simulate once, delay, periodic, and run_until operations using a min-heap ordered by time then insertion order.
Constraints
- periodic operations include a finite run count for deterministic grading.
Examples
Input: ([["once","A",5],["delay","B",2],["run_until",5]])
Expected Output: [[2, 'B'], [5, 'A']]
Explanation: Due tasks run in time then insertion order.
Input: ([["periodic","P",1,3,3],["run_until",10]])
Expected Output: [[1, 'P'], [4, 'P'], [7, 'P']]
Explanation: Periodic task runs a finite requested number of times.
Hints
- Clarify edge cases before coding.
- Keep the return value deterministic.