Problem: Periodic Job Scheduler (Concurrency)
Implement a small in-process job scheduler that can run periodic tasks (functions/callbacks) at a target frequency.
Requirements
-
You must support scheduling tasks specified as a function/callback.
-
Each task is
periodic
, e.g.
50 Hz
(50 times per second). You must convert frequency to a period (time interval).
-
Expose two thread-safe APIs:
-
schedule(taskFn, frequencyHz) -> jobId
-
cancel(jobId) -> void
-
The implementation must be
runnable
(not just a dry run):
-
There is at least
one dedicated worker thread
responsible for executing the tasks.
-
Another thread may call
schedule()
and
cancel()
concurrently while the worker is running.
Behavioral expectations / assumptions (state clearly in your implementation)
-
Use a
monotonic clock
for timing.
-
Multiple jobs may be scheduled at once.
-
If a job is cancelled, it should not run again after cancellation takes effect.
-
Define what happens if a task execution takes longer than its period (e.g., skip missed ticks vs. run immediately to “catch up”).
What to provide
-
The scheduler data structures and synchronization strategy.
-
The worker thread loop logic (sleep/wake strategy).
-
How cancellation is handled safely under concurrency.