Skip to content

Case study: task scheduler

Difficulty: Advanced

Key concepts

  • delayed task
  • periodic task
  • fixed rate
  • priority queue
  • std::set node handles
  • worker pool
  • std::jthread
  • condition variable
  • lost wake-up
  • injected clock
  • cancellation
  • shutdown policy
  • retry with backoff
  • task dependencies
  • all-or-nothing batch
  • How to run work later, and again and again, inside one program: a queue ordered by due time, and a fixed pool of worker threads that take from its front.
  • Why a periodic task should keep the beat of its planned times, what to do about runs it missed, and when planning from the finish time is the better choice.
  • How one mutex and two condition variables are enough to keep a thread pool correct, and why no task may run while the lock is held.
  • What cancelling a task that is already running can honestly mean, and what shutting down must promise before it returns.
  • How an injected clock lets tests move time by hand and never sleep, and the one ordering rule (lock, then notify) without which a moved clock can be missed.
  • Why the scheduler allocates everything a task will ever need when it is scheduled, so that running, rescheduling, and cancelling cannot fail half-way.
  • How a change (retries with backoff, and tasks that wait for other tasks) lands: one rule after each run, a batch that is all or nothing, and a cancellation that spreads without allocating or recursing.

This page follows the order in How to approach a case study. It assumes Asynchronous work, cancellation, and shutdown and Backpressure and bounded queues, and it leans on Thread safety and Testing concurrent code and its limits. Those pages build a worker pool and its tests one idea at a time; this one needs them together, plus time.

“Our service has timers all over the place. Each one started its own thread with a sleep in a loop. Some of those threads never stop, so the service hangs on exit. One report runs at a different minute every day because it waits ten minutes after it finished, not every ten minutes. And when a job throws, its thread dies and nobody notices. Can you design one scheduler that everything uses?”

Three complaints, and each names a part of the design. “Never stop” is shutdown. “A different minute every day” is how a periodic task plans its next run. “Its thread dies and nobody notices” is what a worker does with an exception. A fourth problem is hidden in “a sleep in a loop”: code that sleeps for real time cannot be tested without waiting for real time.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
What is a task? Some code to run. It takes nothing and returns nothing; results go wherever the code puts them. Task is a std::function<void()>. The scheduler owns it.
How far ahead, and how precise? Milliseconds to hours ahead. A few milliseconds late is fine. Durations on a steady clock. No real-time guarantees.
Does “every ten minutes” mean from the start or from the finish? From the planned start: 10:00, 10:10, 10:20, however long each run takes. The next run is planned from the planned time (fixed rate).
If runs were missed (the machine was busy), catch up? No. Run once, late, and go back to the beat. Missed planned times are skipped.
Can a periodic task’s runs overlap? No. Some of them are not safe to run twice at once. The next run is queued only when the current one has ended.
How many threads? A fixed number, set at start-up. We do not want threads appearing under load. A fixed pool of workers, started in the constructor.
Two tasks due at the same moment? The one scheduled first runs first. We want the same order on every run. Ties are broken by a sequence number.
Can a task call the scheduler? Yes. A job schedules its follow-up, and some cancel themselves. No lock may be held while a task runs.
Can we cancel a task while it runs? We cannot stop it in the middle. We want it not to run again. Cancel during a run lets that run finish and stops what follows.
What if a task throws? Record it, keep the worker alive, do not run that task again. (Retries came later; see the change.) A failed state with the error text; the worker catches everything.
What happens on shutdown? Two modes: finish what is already due, or drop everything not started. Either way, wait, then refuse more. ShutdownPolicy::drain and discard; join every thread; refuse with shut_down.
Must tasks survive a restart? No. They are rebuilt when the service starts. Everything is in memory. Persistence is out of scope.
How will we test it? Without waiting. The current tests take minutes because they sleep. An injected Clock, and a ManualClock that tests move by hand.

Three answers decide the shape. “From the planned start” fixes how the next run is computed. “A job schedules its follow-up” means a task must run with no lock held. “Without waiting” means time itself must be a dependency the tests can replace, and that the workers must notice when a test moves it.

Confirmed:

  • Run-once tasks after a delay, and periodic tasks with a first delay and a period.
  • A fixed pool of worker threads.
  • Cancel by task id, at any time, from any thread, including from a task.
  • Failures recorded per task, with the text of what was thrown.
  • Shutdown with a drain or a discard policy.
  • A snapshot of any task’s state.

Assumed (to confirm with the team; see Assumptions):

  • The scheduler is created at start-up and shut down at exit, and the clock it is given outlives it.
  • Tasks are short compared with their periods. A task that blocks for a long time keeps a worker busy, and the pool has no way to grow.
  • Callers do not schedule so many tasks that memory runs out. The queue has no bound; see Backpressure and bounded queues.

Out of scope: priorities other than due time, persistence, several processes or machines, time zones and calendar rules (“every weekday at nine”), and stopping a task in the middle of a run. Retries and dependencies between tasks arrive as a change, below.

Functional requirements.

  • FR-1 Run once. A task scheduled with a delay runs once, on a worker, when its delay has passed.
  • FR-2 Run periodically. A periodic task runs first after its first delay, then at every multiple of its period after that, counted from the planned times. Planned times that have already passed when a run ends are skipped. Two runs of the same task never overlap.
  • FR-3 Order. Of the tasks that are due, the one with the earliest due time runs first; of those due at the same time, the one queued first.
  • FR-4 Cancel. A task cancelled before it starts never runs. A task cancelled while it runs finishes that run and never starts again.
  • FR-5 Failures. A task that throws is recorded as failed, with the text of what it threw, and never runs again. The worker carries on.
  • FR-6 Shutdown. Shutdown refuses new tasks from the moment it is called, runs (drain) or cancels (discard) the tasks not yet started, waits for running tasks, and joins every thread before it returns.
  • FR-7 Status. Anyone can ask for a snapshot of a task: its state, how many times it ran, its error, and why it was cancelled.

Non-functional requirements.

  • NFR-1 Thread-safe. Every public function may be called from any thread, including from inside a task. The two that would wait for the calling task itself (shutdown and wait_until_idle) refuse when called from a task.
  • NFR-2 No task runs under the lock. Neither does any destructor of a task’s callable.
  • NFR-3 Testable without real time. Time comes from an injected Clock. No test sleeps.
  • NFR-4 No failure after acceptance. Once a task is accepted, running, rescheduling, and cancelling it allocate nothing, so they cannot fail half-way.
  • NFR-5 A fixed pool. The number of threads is set at construction and never changes.

FR-2 and NFR-2 carry most of the design. FR-2 decides how the next run is computed; NFR-2 decides the shape of the worker loop.

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Schedule a task.

  • AC-1.1 A run-once task runs once when its delay has passed, and not before.
  • AC-1.2 A zero delay runs at once, without moving the clock.
  • AC-1.3 A periodic task runs at each planned time.
  • AC-1.4 An empty task, a negative delay, and a period that is not positive are refused with a reason, and use no id.
  • AC-1.5 Ids count up from 1; an unknown id has no snapshot.
  • AC-1.6 A scheduler with no workers is refused.

UC-2 Run in order.

  • AC-2.1 The earliest due time runs first, whatever the order of scheduling.
  • AC-2.2 Tasks due at the same time run in the order they were queued.
  • AC-2.3 A task can call the scheduler while it runs.

UC-3 Keep the beat.

  • AC-3.1 The next run is planned from the planned time, not the finish time.
  • AC-3.2 Missed runs are skipped, not run back to back.
  • AC-3.3 A periodic task never overlaps itself, even with idle workers.

UC-4 Cancel.

  • AC-4.1 A task cancelled before it starts never runs.
  • AC-4.2 A periodic task cancelled while running finishes that run and stops.
  • AC-4.3 A run-once task cancelled while running keeps its result.
  • AC-4.4 Cancelling a finished or unknown task says so and changes nothing.
  • AC-4.5 Cancelling twice is harmless.
  • AC-4.6 A periodic task cancelled between runs never runs again.
  • AC-4.7 A finished task’s callable is destroyed at once, with no lock held.

UC-5 Survive failures.

  • AC-5.1 A task that throws is failed, with its message.
  • AC-5.2 The worker survives and runs the next task.
  • AC-5.3 A throw of something that is not an exception is recorded too.
  • AC-5.4 A periodic task that throws is not rescheduled.

UC-6 Shut down.

  • AC-6.1 Discard cancels every task not started and waits for the running one.
  • AC-6.2 Drain runs the tasks already due and cancels the later ones.
  • AC-6.3 No task runs after shutdown returns.
  • AC-6.4 A schedule after shutdown is refused with shut_down.
  • AC-6.5 A second shutdown returns and changes nothing.
  • AC-6.6 Shutdown or wait_until_idle called from a task is refused, and the scheduler keeps running.
  • AC-6.7 The destructor shuts down and discards.

Checks of the non-functional requirements.

  • AC-7.1 Moving the clock always wakes a waiting worker (300 rounds).
  • AC-7.2 The manual clock refuses to go backwards.
  • AC-7.3 The real clock runs a task that is due now.
  • AC-8.1 Tasks run in parallel on every worker.
  • AC-8.2 Many threads scheduling at once get unique ids, and each task runs once.
  • AC-8.3 A cancel racing the start either prevents the run or reports it running.
  • AC-8.4 A cancel from another thread during a periodic run stops it.
  • AC-8.5 Concurrent shutdowns and schedules leave no task pending.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 Queued exactly when pending. A task has an entry in the queue if and only if its state is pending. Kept by make_due (the only code that inserts, and it sets pending), and by run_front, cancel, and shutdown, which take the entry out in the same locked step as they change the state.
  • INV-2 One run at a time per task. A task is queued again only after its run has ended, by the worker that ran it. Kept by run_front.
  • INV-3 No lock during user code. The scheduler’s mutex is never held while a task runs or while its callable is destroyed. Kept by run_front and cancel.
  • INV-4 Final is final. succeeded, failed, and cancelled never change, and a task in one of them is never queued. Kept by the switch in cancel and by run_front, which queues again only from running.
  • INV-5 Every task owns its queue node. From the moment it is accepted, each task owns exactly one node of the queue’s set: inside the queue while pending, in Record::slot otherwise. Kept by add, which allocates it, and by every extract and insert, which only move it.
  • INV-6 Records do not move. Records live in a std::map and are never erased, so a Record& taken under the lock is still valid after the lock is released and taken again. Kept by the map itself.
  • INV-7 After shutdown, nothing runs. Once shutdown returns, no task is pending or running and no worker thread exists. Kept by shutdown, which empties the queue of what must not run and joins every thread.

AC-8.5 checks INV-7 under concurrent shutdowns and schedules: once shutdown has returned, no task is left pending.

The nouns from the answers: task, delay, period, due time, queue, worker, thread, clock, cancel, failure, error, shutdown, policy, id. Filtered:

  • Task is two things: the code (a Task, a std::function) and what the scheduler knows about it (a Record: state, runs, error, period, cancel flag).
  • Delay, period, and due time are a Duration and a TimePoint on the clock.
  • Queue is a std::set of QueueKey values, ordered by due time and then a sequence number.
  • Worker and thread are one thing: a std::jthread running work(). There is no Worker class, because a worker has no state of its own.
  • Clock is an interface with two implementations, SystemClock and ManualClock.
  • Cancel, failure, and shutdown become states and reasons: TaskState, CancelReason, ShutdownPolicy.
  • Id is a TaskId, given out in order.
Entity sketch: who holds what, and who talks to whom
Text description of the diagram

A caller, which may be any thread or a running task, calls schedule, cancel, info, and shutdown on the Scheduler. The Scheduler holds a map of records by id, and a queue of entries ordered by due time and then a sequence number, and guards both with one mutex and two condition variables. A fixed pool of worker threads takes the front of the queue when it is due, runs it without the lock, and updates the task’s record afterwards. The Scheduler asks the Clock for the time and asks it to wait until a time. A ManualClock calls the Scheduler back through a waker each time a test moves it.

Diagram source (Mermaid)
flowchart LR
caller["caller (any thread, or a task)"]
subgraph S ["Scheduler"]
  records["records: map from id to Record"]
  queue["queue: set of (due, seq, id), earliest first"]
  lock["one mutex, two condition variables"]
end
workers["worker threads (std::jthread), a fixed number"]
clock["Clock (SystemClock or ManualClock)"]
caller -- "schedule, cancel, info, shutdown" --> S
workers -- "take the front when due, run it unlocked" --> queue
workers -- "update state after each run" --> records
S -- "now, wait_until" --> clock
clock -- "waker after advance (ManualClock)" --> S

The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Retries and dependencies are added in When the requirements change.

Classes in step 1. Filled diamond: owns. Plain arrow: uses, not owned
Text description of the diagram

Scheduler holds a reference to a Clock it does not own, one mutex, two condition variables named wake_ and changed_, a phase, a map from task id to Record, a set of QueueKey entries, and a vector of jthreads. It offers schedule_once, schedule_every, cancel, shutdown, info, and wait_until_idle. A Record holds the task’s callable, its period, its state, how many times it ran, the exception of a failed run, the cancel reason, a flag for a cancel during a run, the task’s own queue node while it is out of the queue, and an iterator to its entry while it is in the queue. A QueueKey holds a due time, a sequence number, and a task id. Clock is an interface with now, wait_until, add_waker, and remove_waker; SystemClock and ManualClock implement it, and ManualClock adds advance.

Diagram source (Mermaid)
classDiagram
class Scheduler {
  -Clock& clock_
  -mutex mutex_
  -condition_variable wake_
  -condition_variable changed_
  -Phase phase_
  -map~TaskId, Record~ records_
  -set~QueueKey~ queue_
  -vector~jthread~ threads_
  +schedule_once(Duration, Task) Scheduled
  +schedule_every(Duration, Duration, Task) Scheduled
  +cancel(TaskId) CancelResult
  +shutdown(ShutdownPolicy)
  +info(TaskId) optional~TaskInfo~
  +wait_until_idle()
}
class Record {
  +Task task
  +Duration period
  +TaskState state
  +int runs
  +exception_ptr error
  +CancelReason reason
  +bool cancel_requested
  +node_type slot
  +iterator where
}
class QueueKey {
  +TimePoint due
  +uint64 seq
  +TaskId id
}
class Clock {
  <<interface>>
  +now() TimePoint*
  +wait_until(lock, cv, TimePoint)*
  +add_waker(Waker) uint64*
  +remove_waker(uint64)*
}
class ManualClock {
  +advance(Duration)
}
Clock <|.. SystemClock
Clock <|.. ManualClock
Scheduler --> Clock : uses
Scheduler *-- Record : records_
Scheduler *-- QueueKey : queue_
Record ..> QueueKey : owns its node

Ownership is short to state. The scheduler owns the records, the queue, and the threads. Each record owns its task’s callable, except during a run, when the worker running it holds it. The clock is owned by whoever built the scheduler, the composition root, and must outlive it, because the scheduler registers a waker with it and removes it only in its destructor.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

task.hpp
// A task is any callable that takes nothing and returns nothing. The scheduler keeps it in a
// std::function, which owns a copy of the callable (and so of everything a lambda captured).
// std::function needs a copyable callable; C++23's std::move_only_function would also take a
// move-only one, such as a lambda that captures a std::unique_ptr.
using Task = std::function<void()>;
// Each scheduled task gets a number, 1, 2, 3, ... in the order they were accepted.
// 0 means "no task".
using TaskId = std::uint64_t;
// Where a task is in its life:
// pending in the queue, waiting for its due time
// running a worker is running it now
// succeeded a run-once task whose run returned normally (final)
// failed a run threw; the task never runs again (final)
// cancelled it will never run again; CancelReason says why (final)
// A periodic task goes pending -> running -> pending ... until it fails or is cancelled.
enum class TaskState { pending, running, succeeded, failed, cancelled };
enum class CancelReason { none, by_request, shutdown };
// Why schedule_once or schedule_every refused a task. A refused task gets no id.
enum class Refusal { none, shut_down, empty_task, negative_delay, bad_period };
// What cancel did:
// cancelled the task was pending; it will never run
// running a run is in progress. That run is not interrupted (a thread cannot be
// stopped safely from outside) and its result stands: a run-once task
// still ends succeeded or failed. The task never starts again, so a
// periodic task is not rescheduled and ends cancelled (or failed, if
// that last run threw).
// already_finished it had succeeded, failed, or been cancelled already; nothing changes
// unknown_task no task has that id
enum class CancelResult { cancelled, running, already_finished, unknown_task };
// What shutdown does with tasks that have not started:
// drain runs those already due when shutdown is called, and cancels the later ones
// discard cancels them all
// Either way it waits for running tasks to finish, and periodic tasks are not rescheduled.
enum class ShutdownPolicy { drain, discard };
// The answer to a schedule call: an id, or the reason it was refused.
struct Scheduled {
TaskId id = 0; // 0 when refused
Refusal refusal = Refusal::none;
[[nodiscard]] bool ok() const { return refusal == Refusal::none; }
};
// A copy of what the scheduler knows about one task at the moment info() was called.
struct TaskInfo {
TaskState state = TaskState::pending;
int runs = 0; // how many times a worker has started it
std::string error; // what the failed run threw (its what() text), or empty
CancelReason reason = CancelReason::none;
};

Every answer to the team is in this file. A refused task gets an id of 0 and a Refusal that says why, so a caller cannot mistake a refusal for a task. CancelResult::running is the honest answer to “cancel a task while it runs”: the scheduler cannot stop a thread half-way through someone else’s code, so it promises only that the task will not start again. TaskInfo is a copy, taken under the lock, so a caller can read it at leisure while the task changes underneath.

Task is a std::function<void()>, which needs a copyable callable. A lambda that captures a std::unique_ptr cannot be stored in it; C++23’s std::move_only_function lifts that limit. The example stays with C++20, so the comment says so rather than hiding it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

clock.hpp
// The scheduler's time. It is a steady clock: it never jumps backwards when someone changes
// the computer's wall-clock time, which is what a "run in 5 seconds" needs. Its time points
// count from the clock's own start, so the demo can print "t=5s".
using TimePoint = std::chrono::steady_clock::time_point;
using Duration = std::chrono::steady_clock::duration;
// Where the scheduler gets the time, and how it sleeps until a time arrives.
// now the current time.
// wait_until called by a worker that holds `lock` (the scheduler's lock): sleep on `wake`,
// with the lock released while asleep, until `wake` is notified or the time
// reaches `deadline`. It may return early; the caller always checks again.
// add_waker registers a function the clock calls each time its time jumps forward, and
// returns an id for remove_waker. A real clock never jumps, so it never calls
// the function: its wait_until simply times out at the deadline.
class Clock {
public:
using Waker = std::function<void()>;
virtual ~Clock() = default;
[[nodiscard]] virtual TimePoint now() const = 0;
virtual void wait_until(std::unique_lock<std::mutex>& lock, std::condition_variable& wake,
TimePoint deadline) const = 0;
[[nodiscard]] virtual std::uint64_t add_waker(Waker waker) = 0;
virtual void remove_waker(std::uint64_t id) noexcept = 0;
protected:
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
// The real clock, for production. The tests do not use it to wait, because that would mean
// sleeping for real time.
class SystemClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override { return std::chrono::steady_clock::now(); }
void wait_until(std::unique_lock<std::mutex>& lock, std::condition_variable& wake,
TimePoint deadline) const override {
// A timed wait: returns when notified or when the deadline passes. Its result (timed
// out or not) does not matter, because the caller looks at the time again anyway.
static_cast<void>(wake.wait_until(lock, deadline));
}
// Time moves by itself here, so there is nothing to call.
[[nodiscard]] std::uint64_t add_waker(Waker) override { return 0; }
void remove_waker(std::uint64_t) noexcept override {}
};
// A clock that moves only when advance is called, so a test decides exactly when each task
// is due and never sleeps. advance may be called from any thread, including from a task.
class ManualClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override {
// Rebuild a time point from the stored tick count.
return TimePoint{Duration{ticks_.load()}};
}
// Nothing moves this clock while a worker sleeps except advance, and advance notifies
// every waiter through the wakers. So the deadline is not needed: wait for a notify.
void wait_until(std::unique_lock<std::mutex>& lock, std::condition_variable& wake,
TimePoint /*deadline*/) const override {
wake.wait(lock);
}
[[nodiscard]] std::uint64_t add_waker(Waker waker) override {
std::lock_guard guard(mutex_);
// emplace may throw std::bad_alloc; then nothing has changed, because next_id_ is
// only increased after it succeeds.
wakers_.emplace(next_id_, std::move(waker));
return next_id_++;
}
void remove_waker(std::uint64_t id) noexcept override {
std::lock_guard guard(mutex_);
wakers_.erase(id);
}
// Moves the time forward by `step`, then calls every waker. Throws std::invalid_argument
// for a negative step. The wakers are called with this clock's mutex held, so a
// remove_waker waits for a waker that is being called to return: once remove_waker has
// returned, that waker is never called again and its owner may be destroyed.
void advance(Duration step) {
if (step < Duration::zero()) throw std::invalid_argument("time only moves forward");
// The new time is stored before any waker runs, so a woken worker sees it.
// += on a std::atomic is one indivisible read-add-write.
ticks_ += step.count();
std::lock_guard guard(mutex_);
for (const auto& entry : wakers_) entry.second();
}
private:
// In the thread tests one thread advances the clock while workers read it, so the time is
// a std::atomic: a read sees the old time or the new one, never a torn value.
std::atomic<Duration::rep> ticks_{0};
std::mutex mutex_; // guards wakers_ and next_id_
std::map<std::uint64_t, Waker> wakers_;
std::uint64_t next_id_ = 1;
};

The clock is the seam that makes NFR-3 possible, and it has to do more than tell the time. A worker does not only ask “what time is it?”; it also sleeps until a time arrives. So Clock has wait_until, which the scheduler calls with its own lock and condition variable:

  • SystemClock::wait_until is a timed wait. It returns when someone notifies, or when the deadline passes.
  • ManualClock::wait_until ignores the deadline and waits for a notify. With a manual clock, time moves only when advance is called, and advance calls every registered waker, which notifies. A timed wait would be pointless (real time does not matter) and harmful (a worker would wake on real time and see a fake one).

ManualClock stores its time in a std::atomic, because the test thread writes it while worker threads read it, and it stores the new time before calling the wakers, so a woken worker sees it. It calls the wakers with its own mutex held, so that once remove_waker returns no waker is still running and the scheduler may be destroyed. That makes a lock order: the clock’s mutex, then (inside the waker) the scheduler’s. The scheduler never calls the clock’s add_waker or remove_waker while holding its own lock, so the order is never reversed and the two cannot deadlock. See Deadlocks and lock ordering.

A test double for time is usual. What is particular here is the second half, the waker: a fake clock that a worker cannot hear move would leave a worker asleep forever. Testing with time is the subject of Test doubles, seams, and designing for testability.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.hpp
// One entry of the queue: "run task `id` at `due`". `seq` is a counter given out each time
// an entry is added, so entries due at the same time run in the order they were queued,
// not in an order that changes from run to run.
struct QueueKey {
TimePoint due;
std::uint64_t seq = 0;
TaskId id = 0;
friend bool operator<(const QueueKey& a, const QueueKey& b) {
if (a.due != b.due) return a.due < b.due;
return a.seq < b.seq; // seq is unique, so no two keys are equal
}
};
// The priority queue: a std::set kept sorted by (due, seq), so begin() is the next task to
// run. std::priority_queue would give the front too, but it cannot remove an entry from the
// middle, which cancel needs; a set can, in O(log n). With extract and insert, a node can
// also leave the set and go back in later without being freed and allocated again.
using Queue = std::set<QueueKey>;

A priority queue is the textbook answer, and std::priority_queue does give the earliest task in O(log n). But cancel must remove a task from the middle, which std::priority_queue cannot do. The usual workaround is to leave the cancelled entry in place and skip it when it reaches the front (“lazy deletion”); that works, but cancelled tasks then use memory until their due time, which for a task due in a day is a day. A std::set keeps the entries sorted, gives the front as begin(), and removes any entry in O(log n).

The sequence number is what makes AC-2.2 true. Two tasks due at the same moment compare by seq, which only goes up, so they run in the order they were queued, and no two keys are ever equal.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.hpp
// Everything about one task. Records live in a std::map by id and are never removed, so a
// Record& stays valid while the lock is released: a map never moves its elements.
//
// Who owns the callable: the record, except during a run, when the worker running it holds
// it. When a task will never run again, the worker (after the last run) or cancel destroys
// the callable with the lock released. Tasks cancelled by shutdown keep theirs until the
// scheduler is destroyed.
struct Record {
Task task;
Duration period{}; // zero for a run-once task
TaskState state = TaskState::pending;
int runs = 0;
std::exception_ptr error; // what the failed run threw; null if none
CancelReason reason = CancelReason::none;
bool cancel_requested = false; // cancel() was called during a run
Queue::node_type slot; // the task's queue node, kept here while not queued
Queue::iterator where; // its entry in queue_; valid only while pending
};

slot and where are the unusual members. A std::set allocates one node per element. C++17 added extract, which takes a node out of a set without freeing it, and an insert that puts a node back without allocating. So each task gets its node once, when it is accepted, and from then on the node only moves: into the queue when the task is pending, into Record::slot otherwise. That is INV-5, and it is why NFR-4 holds: running, rescheduling, and cancelling never allocate, so none of them can throw std::bad_alloc half-way through. where is the task’s position in the set while it is pending, so cancel can find it without a search.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.hpp
// mutex_ guards every member below it except the last three: waker_id_, worker_ids_ and
// threads_ are written only by the constructor, before any other thread can use the
// scheduler, and threads_ is joined only by the one thread that runs shutdown's work.
// One mutex for the whole scheduler is simple and enough here: the lock is held only for
// short bookkeeping, never while a task runs.
Clock& clock_;
mutable std::mutex mutex_;
std::condition_variable wake_; // workers sleep here: "the queue or the time changed"
std::condition_variable changed_; // wait_until_idle and a second shutdown sleep here:
// "a run ended or a task left the queue"
Phase phase_ = Phase::running;
std::map<TaskId, Record> records_;
Queue queue_;
TaskId next_id_ = 1;
std::uint64_t next_seq_ = 0;
int running_ = 0; // tasks being run right now
std::uint64_t waker_id_ = 0;
std::vector<std::thread::id> worker_ids_;
// Declared last, so it is destroyed first. By then shutdown has joined every thread.
std::vector<std::jthread> threads_;

There is one mutex for the whole scheduler. Every piece of bookkeeping is short (a map lookup, a set insert), and no task ever runs under it, so one lock is unlikely to be a bottleneck for a pool of a few threads (nothing was measured for this page); it is also far easier to reason about than several. Not every step under it is short, though: shutdown walks the whole queue with the lock held, and in step 2 it also walks every record the scheduler has ever had, and a cancel that spreads down a long chain of dependents visits each one, all while every worker and caller waits. There are two condition variables because there are two kinds of sleeper. Workers wait on wake_ for “the queue or the time changed”; wait_until_idle and a second caller of shutdown wait on changed_ for “a run ended or a task left the queue”. With one variable, every notify would have to be notify_all to everyone, and each sleeper would wake for news that does not concern it.

threads_ is declared last on purpose. Members are destroyed in reverse order, so the threads go first. By then shutdown has joined them all, so their destructors have nothing to do; if it had not, a std::jthread destructor would try to join a worker that is still using the members around it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Accepts a task (period zero: run once). The refusals are checked first, so a refused task
// changes nothing.
Scheduled Scheduler::add(Duration delay, Duration period, Task task) {
if (!task) return {0, Refusal::empty_task};
if (delay < Duration::zero()) return {0, Refusal::negative_delay};
std::lock_guard lock(mutex_);
if (phase_ != Phase::running) return {0, Refusal::shut_down};
// Allocate everything the task will ever need before changing any state: its queue node,
// then its record. If either throws std::bad_alloc the scheduler is exactly as it was
// (try_emplace adds nothing when it throws), and the error reaches the caller.
Queue::node_type slot = new_slot();
const TaskId id = next_id_;
Record& rec = records_.try_emplace(id).first->second;
// Nothing below allocates or throws.
++next_id_;
rec.task.swap(task); // the record now owns the callable; swap never throws
rec.period = period;
rec.slot = std::move(slot);
make_due(rec, id, clock_.now() + delay);
return {id, Refusal::none};
}

The order inside add is the whole point:

  1. The checks that need no lock come first: an empty task and a negative delay. schedule_every has already refused a period that is not positive.
  2. Under the lock, a scheduler that is shutting down refuses. Checking phase_ under the same lock as the insert means no task can slip in after shutdown has emptied the queue.
  3. Everything that can throw happens next: new_slot allocates the queue node, and try_emplace allocates the record. If either throws, nothing has changed yet and the std::bad_alloc reaches the caller.
  4. Then the steps that cannot throw: take the id, swap the callable into the record (a swap of two std::function objects never throws), store the period and the node, and make_due.

new_slot makes a node in a scratch set and extracts it. It is the only portable way to get an empty node of a set’s type. The scratch set is destroyed at the end of the function, empty.

make_due puts the node back in the queue and notifies wake_, with the lock held. A newly queued task may be earlier than the one a worker is sleeping until, and only a notify makes that worker look again.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// The loop each worker thread runs until shutdown. It holds the lock all the time except while
// it sleeps (a condition-variable wait releases the lock and takes it again on waking) and
// while it runs a task (run_front releases it). A wait can return without a notify (a
// "spurious wake-up"), so after every wait it starts again from the top and looks afresh.
// noexcept: if anything in here threw, std::terminate would stop the program, rather than
// leave a worker silently gone.
void Scheduler::work() noexcept {
std::unique_lock lock(mutex_);
for (;;) {
if (queue_.empty()) {
// Nothing queued. Once shutdown has begun nothing more can be queued, so the
// thread ends; until then, sleep until something is scheduled.
if (phase_ != Phase::running) return;
wake_.wait(lock);
continue;
}
const TimePoint due = queue_.begin()->due;
if (due > clock_.now()) {
// The front task is not due yet: sleep until it is, or until something changes
// (an earlier task, a cancel, the manual clock moving). After shutdown begins the
// queue holds only due tasks, so a worker never waits here then.
clock_.wait_until(lock, wake_, due);
continue;
}
run_front(lock);
}
}

The loop has three cases, and after every wait it starts again from the top. A condition-variable wait can return with no notify at all (a “spurious wake-up”), and even after a real notify another worker may already have taken the task. So the loop never assumes why it woke; it looks.

The wait for “the front is due” goes through the clock. That is the only place the worker’s sleep depends on time, and it is why a ManualClock can run the whole scheduler with no real waiting.

work is noexcept. Nothing in it should throw, because run_front catches what tasks throw. If something did throw (a bug), the program stops with std::terminate, which is loud, instead of a worker thread ending quietly and the pool shrinking with no one noticing. That quiet shrinking is the team’s third complaint.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Runs the task at the front of the queue. Called by a worker with the lock held; returns with
// it held. The task runs with the lock released, for two reasons. Other workers, and callers
// of schedule or cancel, must not wait while a slow task runs. And a task may call the
// scheduler (schedule a follow-up, cancel itself): with the lock held, that call would try to
// lock a mutex its own thread already holds, which deadlocks.
void Scheduler::run_front(std::unique_lock<std::mutex>& lock) noexcept {
// Leave the queue and become running in one locked step, so cancel sees the task as
// pending or as running, never in between.
Queue::node_type node = queue_.extract(queue_.begin());
const QueueKey key = node.value();
Record& rec = record(key.id);
rec.slot = std::move(node); // kept for the next run of a periodic task
rec.state = TaskState::running;
++rec.runs;
++running_;
Task task;
task.swap(rec.task); // the worker holds the callable during the run
lock.unlock();
std::exception_ptr error;
try {
task();
} catch (...) {
// Whatever the task throws stops here and is recorded. If it left the thread's
// function, std::terminate would end the whole program. current_exception() does
// not throw.
error = std::current_exception();
}
lock.lock();
bool again = false;
if (error) {
// A failure ends the task, periodic or not: the scheduler cannot tell whether the next
// run would fail the same way, and repeating a failure quietly would hide it.
rec.state = TaskState::failed;
rec.error = error;
} else if (rec.period == Duration::zero()) {
rec.state = TaskState::succeeded;
} else if (rec.cancel_requested) {
rec.state = TaskState::cancelled;
rec.reason = CancelReason::by_request;
} else if (phase_ != Phase::running) {
rec.state = TaskState::cancelled;
rec.reason = CancelReason::shutdown;
} else {
make_due(rec, key.id, next_slot(key.due, rec.period, clock_.now()));
rec.task.swap(task); // hand the callable back for the next run
again = true;
}
if (!again) {
// The task will never run again, so free its callable now, but with the lock released:
// the callable's destructor (and those of whatever a lambda captured) may call the
// scheduler. The run counts as running until this is done, so when wait_until_idle
// returns, the callable of every task whose last run has ended has been destroyed.
lock.unlock();
task = nullptr;
lock.lock();
}
--running_;
changed_.notify_all(); // wait_until_idle may be waiting for this run to end
}
How this code works: run_front on the demo's heartbeat at 35 seconds

The step 1 demo has one worker and a heartbeat (task 2) every 10 seconds from 10 seconds. After its run at 10 seconds it was queued for 20. The demo then moves the clock straight from 10 to 35 seconds. Here is what run_front does, read from the code:

  1. Out of the queue, in one locked step. The front entry is (due 20s, task 2). extract takes its node out, the node goes into rec.slot, the state becomes running, runs becomes 2, and running_ becomes 1. A cancel arriving now sees running, never a task that is neither queued nor running.
  2. The worker takes the callable. task.swap(rec.task) moves the std::function into a local. While the task runs, the record holds nothing, and nobody else can destroy the callable under the worker.
  3. Unlock, run, lock. The heartbeat prints t=35s heartbeat. Any exception would be caught and kept as a std::exception_ptr.
  4. Decide. No error, a non-zero period, no cancel request, and the scheduler is running, so the last branch: make_due with next_slot(20s, 10s, 35s), which is 40 seconds (worked through in the next section). The callable goes back into the record, and again is true.
  5. Count down. running_ goes back to 0 and changed_ is notified, which is what lets the demo’s wait_until_idle return.

At 40 seconds the same steps run again, with runs at 3 and the next run planned at 50 seconds.

The order of the four branches matters. An error comes first, so a periodic task that throws is failed, not rescheduled (AC-5.4), even if it was also cancelled. A run-once task ends succeeded even if cancel was called during its run (AC-4.3): the work was done, and saying “cancelled” would be a lie about it. Only a periodic task can be stopped by cancel_requested or by shutdown, because only a periodic task would otherwise run again.

When the task will never run again, its callable is destroyed straight away, with the lock released. A lambda’s captures can be anything: a std::shared_ptr whose last copy closes a file, or an object whose destructor calls the scheduler. Destroying it under the lock would deadlock in the second case. AC-4.7 checks this with a callable that holds the only reference to an object whose destructor calls accepting(), which takes the lock. Destroyed under the lock, it would make the test hang.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// When a periodic task runs next. Its runs are planned at first, first + period,
// first + 2 * period, ... and the next run is the first planned time after `now` (when the
// run just finished). Counting from the planned time rather than from the finish keeps a
// steady beat: a task every 10 seconds whose runs take 2 seconds starts at 10, 20, 30, not
// at 10, 22, 34. If planned times have already gone by (the run was late or took more than a
// period), those runs are skipped, not run back to back to catch up.
TimePoint next_slot(TimePoint planned, Duration period, TimePoint now) {
TimePoint next = planned + period;
if (next <= now) {
// (now - next) / period divides two durations: a whole number of periods, rounded
// down. Adding one more period than that lands on the first planned time after now.
next += ((now - next) / period + 1) * period;
}
return next;
}
How this code works: next_slot on the demo's heartbeat

The heartbeat’s planned times are 10, 20, 30, 40, 50, and so on. Each call below is next_slot(planned, 10s, now), where now is the time when the run ended. The demo’s tasks take no time on the manual clock, so now is the time the run started.

Run at planned planned + period Is it <= now? Next run
10s 10s 20s no 20s
35s 20s 30s yes, 30s <= 35s 30s + ((35s - 30s)/10s + 1) × 10s = 30s + (0 + 1) × 10s = 40s
40s 40s 50s no 50s

The run planned for 20 seconds ran late, at 35. The one planned for 30 had already gone by, so it is skipped (AC-3.2), and the beat goes on at 40, not at 45. (now - next) / period divides one duration by another, which gives a plain whole number rounded down, here 0.

AC-3.1 checks the other half: each run moves the clock on by 3 seconds while it runs, and the runs still start at 10, 20, and 30, not 10, 23, and 36.

“From the planned time” (fixed rate) is the right choice for this team, because they asked for 10:00, 10:10, 10:20. It is not always right. A task that cleans up after itself, or polls a service that needs a rest between calls, may want a fixed delay from the end of one run to the start of the next; a run that takes most of its period then gets no rest at all under fixed rate. The exercise at the end adds that as an option.

A periodic task never overlaps itself (AC-3.3), with no extra code: its next run is queued only after the current one ends, by the worker that ran it. Four idle workers cannot pick up a task that is not in the queue.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
CancelResult Scheduler::cancel(TaskId id) {
// Declared before the lock, so it is destroyed after the lock is released (locals are
// destroyed in reverse order). It receives the callable of a task cancelled here.
Task doomed;
std::lock_guard lock(mutex_);
const auto found = records_.find(id);
if (found == records_.end()) return CancelResult::unknown_task;
Record& rec = found->second;
switch (rec.state) {
case TaskState::pending:
rec.slot = queue_.extract(rec.where); // out of the queue; the task keeps its node
rec.state = TaskState::cancelled;
rec.reason = CancelReason::by_request;
doomed.swap(rec.task);
changed_.notify_all(); // a due task left the queue: we may be idle now
return CancelResult::cancelled;
case TaskState::running:
// The worker reads this flag when the run ends; see CancelResult::running.
rec.cancel_requested = true;
return CancelResult::running;
case TaskState::succeeded:
case TaskState::failed:
case TaskState::cancelled:
return CancelResult::already_finished;
}
return CancelResult::already_finished; // not reached: the switch covers every state
}

cancel is a switch over the state, with every state named, so a compiler warns if a new state is added and not handled. Two details are about lifetime:

  • doomed is declared before the lock. Local objects are destroyed in reverse order of declaration, so the lock is released first and the callable destroyed after, with no lock held, for the same reason as in run_front.
  • The node goes back into rec.slot. The task keeps it even though it will never use it again, because freeing it would mean the set allocates and frees at run time. Records are never erased (INV-6), so this memory is held until the scheduler is destroyed: see the limitations.

changed_ is notified because a pending task that was due has left the queue, so the scheduler may now be idle.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
void Scheduler::shutdown(ShutdownPolicy policy) {
if (on_worker_thread()) throw std::logic_error("shutdown called from a task");
std::unique_lock lock(mutex_);
if (phase_ != Phase::running) {
// Another thread has begun the shutdown, or it is done: wait until it is done.
changed_.wait(lock, [this] { return phase_ == Phase::stopped; });
return;
}
phase_ = Phase::stopping; // from here on, add() refuses and nothing is rescheduled
// Take out of the queue every task that must not run: all of them for discard, and for
// drain those not yet due at this moment. With a manual clock, waiting for a later task
// could wait forever. What stays in the queue is due, so the workers run it and then end.
const TimePoint cutoff = clock_.now();
for (auto it = queue_.begin(); it != queue_.end();) {
if (policy == ShutdownPolicy::drain && it->due <= cutoff) {
++it;
continue;
}
Record& rec = record(it->id);
const auto after = std::next(it); // extract invalidates `it` only
rec.slot = queue_.extract(it);
rec.state = TaskState::cancelled;
rec.reason = CancelReason::shutdown;
it = after;
}
wake_.notify_all(); // sleeping workers wake, run what is left, and end
changed_.notify_all(); // tasks left the queue
// Join with the lock released: the workers need it to finish. Only the thread that moved
// phase_ to stopping gets here, so no thread is joined twice.
lock.unlock();
for (std::jthread& worker : threads_) worker.join();
lock.lock();
phase_ = Phase::stopped;
changed_.notify_all(); // release any second caller of shutdown
}
How this code works: shutdown(drain) at the end of the step 1 demo

At 40 seconds the demo schedules a task called “late” (task 5) with a delay of 20 seconds, so it is due at 60, then calls shutdown(ShutdownPolicy::drain). The heartbeat is pending, due at 50. Read from the code:

  1. Refuse from now on. phase_ becomes stopping. Any add from here returns Refusal::shut_down, which is the demo’s schedule after shutdown: refused, shut down.
  2. The cutoff is now, 40 seconds. Drain keeps entries with due <= 40s. There are none: the heartbeat is due at 50 and late at 60. Both are extracted, their nodes go back to their records, and both become cancelled with reason shutdown.
  3. Wake everyone. The workers wake, find the queue empty with the phase not running, and return from work.
  4. Join. With the lock released, shutdown joins every thread. Then phase_ becomes stopped and a second caller, if any, is released.

So the final states read heartbeat (task 2): cancelled, runs 3, reason shutdown and late (task 5): cancelled, runs 0, reason shutdown.

Why is the cutoff “now” and not “run everything”? With a manual clock, a task due at 60 seconds would never become due, and drain would wait forever. With a real clock, it would wait an hour for a task due in an hour, which is not what anyone means by “finish what you were doing”. So drain runs what is already late, and nothing else.

A task that is running when shutdown begins finishes its run; if it is periodic, run_front sees phase_ != Phase::running and cancels it with reason shutdown instead of queuing it again. That is the promise of FR-6: when shutdown returns, every thread has been joined, so no task can still be running, and none can start (INV-7).

shutdown throws std::logic_error when called from a worker thread (AC-6.6). A task that called it would join its own thread, which cannot end until the task returns: a deadlock with one thread in it. on_worker_thread compares the caller’s thread id with the ids recorded in the constructor.

The waker, and the wake-up that could be lost

Section titled “The waker, and the wake-up that could be lost”

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Called by a ManualClock after each advance, on the thread that advanced it. Taking the lock
// before notifying is what prevents a lost wake-up. A worker goes to sleep in two steps: it
// reads the time while holding the lock, then waits, which releases the lock. If the clock
// moved and notified between those two steps, no one would be waiting yet: the notify would be
// lost, and the worker would sleep through a task that is now due. Because this function needs
// the lock, it runs either before the worker reads the time (and the worker sees the new time,
// which advance stored before calling this) or after the wait has released the lock (and the
// worker, already waiting, gets the notify).
void Scheduler::time_moved() noexcept {
std::lock_guard lock(mutex_);
wake_.notify_all();
}

This function is two lines, and the first is the reason it exists. Without the lock, here is an order of events that loses the wake-up:

Step Worker thread Test thread
1 holds the lock; reads now() = 0s; front due at 5s
2 decides to wait (has not yet started waiting) advance(5s): time is now 5s
3 waker calls notify_all: nobody is waiting yet
4 wait(lock): releases the lock and sleeps
5 sleeps on, with a task that is due wait_until_idle waits for a run that never starts

With the lock, step 3 cannot happen between steps 1 and 4: the worker holds the lock from reading the time until the wait releases it. So time_moved runs either before step 1 (and the worker reads 5 seconds) or after step 4 (and the worker, now waiting, is woken). The rule is general: change the condition, or at least pass through the lock, before you notify. AC-7.1 runs this 300 times with two workers, and AC-12.1 (listed with the change, and in both steps’ tests) forces the bad order on purpose.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
void Scheduler::wait_until_idle() {
if (on_worker_thread()) throw std::logic_error("wait_until_idle called from a task");
std::unique_lock lock(mutex_);
// idle() is checked with the lock held, and everything that can make it true (a run
// ending, a task leaving the queue) changes state and notifies changed_ under the same
// lock, so this cannot miss its wake-up.
changed_.wait(lock, [this] { return idle(); });
}
// True when no task is running and the front of the queue (if any) is not yet due. The caller
// holds the lock.
bool Scheduler::idle() const {
return running_ == 0 && (queue_.empty() || queue_.begin()->due > clock_.now());
}

wait_until_idle exists for tests and for the demo. After moving a ManualClock, a test calls it instead of sleeping, and when it returns every task that was due has run. Two details make that promise exact:

  • “Idle” means no task is running and the front is not due. A due task that no worker has picked up yet still counts as work.
  • A run counts as running until its callable has been destroyed (--running_ comes after task = nullptr in run_front). The code agent’s report says this order came from a ThreadSanitizer finding while the example was built; that run was not repeated for this page. Reading the code shows the race it closes: if running_ went down first, a test could see “idle”, end, and destroy the objects a lambda had captured by reference while the worker was still destroying that lambda.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
Scheduler::Scheduler(Clock& clock, std::size_t workers) : clock_(clock) {
if (workers == 0) throw std::invalid_argument("a scheduler needs at least one worker");
// Allocate before starting anything, so the push_back below cannot throw.
worker_ids_.reserve(workers);
threads_.reserve(workers);
// The lambda captures `this`; the destructor removes it before the scheduler is gone.
waker_id_ = clock_.add_waker([this] { time_moved(); });
try {
for (std::size_t i = 0; i < workers; ++i) {
threads_.emplace_back([this] { work(); });
worker_ids_.push_back(threads_.back().get_id());
}
} catch (...) {
// A thread failed to start. A constructor that throws gets no destructor call, so
// stop and join the threads already started here, then let the error through. (A
// std::jthread's own destructor would join, but these workers do not watch its stop
// token, so they would never end.)
{
std::lock_guard lock(mutex_);
phase_ = Phase::stopped;
}
wake_.notify_all();
for (std::jthread& worker : threads_) worker.join();
clock_.remove_waker(waker_id_);
throw;
}
}
Scheduler::~Scheduler() {
shutdown(ShutdownPolicy::discard);
// After this, the clock never calls the waker, whose lambda points at this object.
clock_.remove_waker(waker_id_);
}

Starting a thread can fail with std::system_error. If the third of four threads fails, two are running work() with this, and a constructor that throws gets no destructor call. So the catch stops and joins them by hand, then rethrows. A std::jthread destructor would join too, but it requests a stop first through its std::stop_token, and these workers do not watch that token; they watch phase_. The destructor is one line, shutdown(discard), then remove_waker, so a scheduler that goes out of scope never leaves a thread behind (AC-6.7).

This is RAII for threads: the object that started them is the one that stops them, and the destructor guarantees it. The team’s first complaint, threads that never stop, is what happens without it.

Rule Where it is kept
refusals use no id and change nothing (AC-1.4) add: checks before any allocation, id taken after
earliest due first, ties in queue order (FR-3) QueueKey::operator<, and work taking begin()
fixed rate, missed runs skipped (FR-2) next_slot
no overlap (AC-3.3) run_front queues the next run only after the run ends
no lock during user code (NFR-2) run_front unlocks around the run and the callable’s destruction; cancel’s doomed
no allocation after acceptance (NFR-4) new_slot in add; extract and insert everywhere else
cancel during a run (FR-4) cancel sets cancel_requested; run_front reads it
failures recorded, worker survives (FR-5) try and catch (...) in run_front
shutdown refuses, drains or discards, joins (FR-6) shutdown, and the phase_ check in add
no lost wake-up (AC-7.1) time_moved takes the lock before notifying
The states of one task in step 1, and what moves it on
Text description of the diagram

A task starts pending when add accepts it. From pending it goes to running when it is due and a worker takes it, or to cancelled if cancel or shutdown takes it out of the queue first. From running, a periodic task whose run ended normally goes back to pending, queued for its next planned time. A run-once task whose run returned goes to succeeded. A run that threw goes to failed, periodic or not. A periodic task that was cancelled during its run, or whose run ended after shutdown began, goes to cancelled. Succeeded, failed, and cancelled are final.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> pending : accepted (add)
pending --> running : due, a worker takes it (run_front)
pending --> cancelled : cancel, or shutdown
running --> pending : periodic, run ended, queued again
running --> succeeded : run-once, run returned
running --> failed : run threw
running --> cancelled : periodic, cancel during the run or shutdown
succeeded --> [*]
failed --> [*]
cancelled --> [*]
One run of the heartbeat at 35 seconds, with a manual clock and one worker
Text description of the diagram

The worker holds the lock, sees the front task is due at 20 seconds while the time is 10, and waits through the ManualClock, which releases the lock. The test thread calls advance with 25 seconds. The clock stores 35 seconds, then calls the scheduler’s waker, time_moved, which takes the lock, notifies wake_, and releases it. The worker wakes holding the lock, sees the front is due, and calls run_front, which unlocks, runs the heartbeat, and locks again. It computes the next slot from the planned 20 seconds, period 10, now 35, which is 40, and queues the task with make_due. It sets running_ back to 0 and notifies changed_, and the test’s wait_until_idle returns.

Diagram source (Mermaid)
sequenceDiagram
participant T as test (main thread)
participant C as ManualClock
participant S as Scheduler
participant W as worker
W->>S: lock, front due at 20s, now is 10s
W->>C: wait_until (releases the lock)
T->>C: advance(25s)
C->>C: store 35s
C->>S: waker: time_moved
S->>S: lock, notify wake_, unlock
S-->>W: wakes, holds the lock
W->>S: front due at 20s, now is 35s: run_front
W->>W: unlock, run heartbeat, lock
W->>S: next_slot(20s, 10s, 35s) = 40s, make_due
W->>S: running_ to 0, notify changed_
T->>S: wait_until_idle returns
  1. advance stores the new time before calling any waker, so the worker that wakes reads 35 seconds (the clock’s comment says why).
  2. The waker takes the scheduler’s lock, so it cannot fall between the worker’s read of the time and its wait (the lost wake-up table).
  3. The task runs with the lock released (NFR-2), and the next run is planned from 20 seconds, not 35 (FR-2).
  4. wait_until_idle returns only after running_ is back to 0, and the front (40 seconds) is not due.

The scheduler is a thread pool fed by a time-ordered queue. Callers are producers, workers are consumers, and the queue sits between them, guarded by one mutex with condition variables to sleep on (the shape often called a monitor). The clock is a dependency passed in, which is what lets tests replace it. Those are the only structures here, and each one answers a question from the team.

The mistakes below are the ones the team’s old timers made, and the ones a first version of a scheduler usually makes. Each sketch is a fragment written against a small stand-in class, not code from the example. They were compiled with -fsyntax-only by g++ and clang++ for this page, and were not run.

  • No Worker class. A worker has no state of its own; it is a thread running work(). A class would add a name and nothing else.
  • No Strategy object for the shutdown policy or the period. Two policies, each a few lines in one function, fit an enum. A Strategy would be worth it if callers had to supply their own policy.
  • No thread per task. That is the design the team is leaving. A fixed pool bounds the number of threads (NFR-5); the price is that a task that blocks keeps a worker busy.
  • No lock-free queue. The lock is held only for short bookkeeping. Nothing measured here suggests it is the bottleneck, and a lock-free priority queue with cancellation is far harder to get right. No benchmark was run for this page.
  • No priorities beyond due time. The team asked for none. Adding them means deciding what “earlier but lower priority” means, which is a requirements question first.
  • No std::async or std::future per task. Callers asked for a state and an error, which info gives, not a value to wait for.

An order that works, each step leaving something that compiles and can be tested. (This is a suggested order for building it yourself, not a record of how the example was written.)

  1. Types and the clock. task.hpp and clock.hpp, with a ManualClock from the start, so the very first test can move time.
  2. One worker, run-once tasks. add, work, run_front with the lock released around the run, and wait_until_idle. Tests 1.1, 1.2, 2.1, and 2.2.
  3. Periodic tasks. next_slot and the “queue again” branch. The tests in group 3, with a task that moves the clock while it runs, to show the beat holds.
  4. Failures. The try and catch around the run. Group 5.
  5. Cancel. The switch, cancel_requested, and doomed. Group 4.
  6. Shutdown and the destructor. Phases, the cutoff, joining. Group 6.
  7. Many workers, many callers. Little new code: one lock around all bookkeeping makes the design thread-safe from step 2. Groups 7 and 8 check it under contention, then the sanitizer presets.
  8. Node handles. Replacing a plain insert of a key with a node each task owns can come last, because it changes no behaviour: the same tests pass before and after, and it is what makes NFR-4 true.

The step 1 demo runs on a ManualClock with one worker, so its output is the same on every run.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
ManualClock clock;
Scheduler scheduler(clock, 1);
// Each task prints when it runs. The worker prints while the main thread is blocked in
// wait_until_idle, so the two never print at the same time.
auto say = [&clock](const std::string& what) {
std::cout << " t=" << seconds_of(clock.now()) << "s " << what << "\n";
};
// Moves the clock forward, then waits until every task now due has run.
auto advance_to = [&](seconds when) {
// Print first: once the clock moves, the worker may print at once.
std::cout << "clock at " << when.count() << "s\n";
clock.advance(when - duration_cast<seconds>(clock.now().time_since_epoch()));
scheduler.wait_until_idle();
};
const TaskId report = scheduler.schedule_once(5s, [&] { say("report: sent"); }).id;
const TaskId beat = scheduler.schedule_every(10s, 10s, [&] { say("heartbeat"); }).id;
const TaskId flaky =
scheduler.schedule_once(7s, [&] { throw std::runtime_error("disk full"); }).id;
const TaskId cleanup = scheduler.schedule_once(30s, [&] { say("cleanup"); }).id;
std::cout << "scheduled report, heartbeat (every 10s from 10s), flaky, cleanup\n";
std::cout << "cancel cleanup: " << to_string(scheduler.cancel(cleanup)) << "\n";
advance_to(5s);
advance_to(7s);
show(scheduler, flaky, "flaky");
// The single worker survived the throw, so later tasks still run.
advance_to(10s);
// A jump past two planned runs (20s and 30s): the heartbeat runs once, late, and the
// missed runs are skipped. The next one is planned for 40s, not 45s.
advance_to(35s);
advance_to(39s);
advance_to(40s);
const TaskId late = scheduler.schedule_once(20s, [&] { say("late"); }).id;
std::cout << "shutdown (drain)\n";
scheduler.shutdown(ShutdownPolicy::drain);
const Scheduled refused = scheduler.schedule_once(0s, [&] { say("too late"); });
std::cout << "schedule after shutdown: "
<< (refused.ok() ? std::string("accepted")
: "refused, " + std::string(to_string(refused.refusal)))
<< "\n";
std::cout << "final states:\n";
show(scheduler, report, "report");
show(scheduler, beat, "heartbeat");
show(scheduler, flaky, "flaky");
show(scheduler, cleanup, "cleanup");
show(scheduler, late, "late");
}
Expected output
scheduled report, heartbeat (every 10s from 10s), flaky, cleanup
cancel cleanup: cancelled
clock at 5s
t=5s report: sent
clock at 7s
flaky (task 3): failed, runs 1, error "disk full"
clock at 10s
t=10s heartbeat
clock at 35s
t=35s heartbeat
clock at 39s
clock at 40s
t=40s heartbeat
shutdown (drain)
schedule after shutdown: refused, shut down
final states:
report (task 1): succeeded, runs 1
heartbeat (task 2): cancelled, runs 3, reason shutdown
flaky (task 3): failed, runs 1, error "disk full"
cleanup (task 4): cancelled, runs 0, reason by request
late (task 5): cancelled, runs 0, reason shutdown

How to read it:

  • Before any time passes, cleanup (task 4) is cancelled. It was pending, so it is cancelled with reason by request and never runs.
  • At 5 seconds, the report runs and succeeds.
  • At 7 seconds, flaky throws disk full. It is failed with that text, and the only worker is still there for the next task.
  • At 10 seconds, the heartbeat’s first run, planned at 10.
  • At 35 seconds, one late run (planned at 20), not three. The run planned at 30 is skipped, and the next is planned at 40, as the next_slot walkthrough worked out.
  • At 39 seconds, nothing: 40 has not come yet.
  • At 40 seconds, the heartbeat is back on its beat.
  • Shutdown (drain) at 40 seconds finds nothing due: the heartbeat (due at 50) and late (due at 60) are cancelled with reason shutdown. A schedule after it is refused.

The 40 step 1 tests use the example’s small test framework and run on a ManualClock. None of them sleeps. Most use this helper, which pairs a clock and a scheduler and turns “move the clock” into “move the clock and wait until everything due has run”:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// A manual clock and a scheduler on it, declared in that order so the scheduler (which uses
// the clock) is destroyed first. advance moves the clock and waits until every task now due
// has run: that replaces "sleep and hope".
struct World {
ManualClock clock;
Scheduler scheduler;
explicit World(std::size_t workers = 1) : scheduler(clock, workers) {}
void advance(Duration step) {
clock.advance(step);
scheduler.wait_until_idle();
}
[[nodiscard]] TaskInfo info(TaskId id) const { return scheduler.info(id).value(); }
[[nodiscard]] long long now() const {
return duration_cast<seconds>(clock.now().time_since_epoch()).count();
}
};

The clock is declared before the scheduler, so the scheduler is destroyed first (members are destroyed in reverse order), as the clock’s contract requires.

The beat (UC-3). The first test moves the clock forward by 3 seconds inside each run, so a scheduler that planned from the finish would show 10, 23, 36:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_3_1_the_next_run_is_planned_from_the_planned_time_not_the_finish_time) {
World w;
Log log;
// Each run "takes" 3 seconds: the task moves the clock itself while it runs.
static_cast<void>(w.scheduler.schedule_every(10s, 10s, [&] {
log.add(std::to_string(w.now()));
w.clock.advance(3s);
}));
w.advance(10s); // runs at 10, finishes at 13
LLD_CHECK_EQ(w.now(), 13LL);
w.advance(7s); // t=20: due again (planned 10 + 10), not at 23
w.advance(7s); // t=30 (the run at 20 moved the clock to 23)
LLD_CHECK_EQ(joined(log.lines()), std::string("10 20 30"));
}
LLD_TEST(ac_3_2_missed_runs_are_skipped_not_run_back_to_back) {
World w;
std::atomic<int> runs{0};
const TaskId id = w.scheduler.schedule_every(10s, 10s, [&] { ++runs; }).id;
w.advance(35s); // planned 10, 20, 30 have all passed: one late run
LLD_CHECK_EQ(runs.load(), 1);
w.advance(4s); // t=39: the next run is planned at 40, not 45
LLD_CHECK_EQ(runs.load(), 1);
w.advance(1s);
LLD_CHECK_EQ(runs.load(), 2);
LLD_CHECK_EQ(w.info(id).runs, 2);
}
LLD_TEST(ac_3_3_a_periodic_task_never_overlaps_itself) {
World w(4);
std::atomic<int> inside{0};
std::atomic<int> most{0};
std::atomic<int> runs{0};
static_cast<void>(w.scheduler.schedule_every(1s, 1s, [&] {
const int now_inside = ++inside;
if (now_inside > most) most = now_inside;
// While this run is in progress, move the clock past several more planned times.
// Three idle workers are free, but the next run is queued only after this one ends.
if (++runs == 1) w.clock.advance(5s);
--inside;
}));
w.advance(1s);
w.advance(1s);
LLD_CHECK_EQ(most.load(), 1);
LLD_CHECK_EQ(runs.load(), 2);
}

Cancel while running (UC-4). To cancel a task while it runs, the test must know it is running. The simplest way is to have the task cancel itself, from inside its own run, so “running” is a fact, not a hope. The id is captured by reference and filled in before the clock moves, so the task reads the right value:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_4_2_a_periodic_task_cancelled_while_running_finishes_that_run_and_stops) {
World w;
std::atomic<int> runs{0};
CancelResult answer = CancelResult::unknown_task;
TaskId id = 0;
id = w.scheduler.schedule_every(1s, 1s, [&] {
++runs;
answer = w.scheduler.cancel(id); // cancel itself, in the middle of its run
}).id;
w.advance(1s);
LLD_CHECK_EQ(answer, CancelResult::running);
LLD_CHECK_EQ(w.info(id).state, TaskState::cancelled);
LLD_CHECK_EQ(w.info(id).reason, CancelReason::by_request);
w.advance(10s);
LLD_CHECK_EQ(runs.load(), 1);
}
LLD_TEST(ac_4_3_a_run_once_task_cancelled_while_running_keeps_its_result) {
World w;
TaskId good = 0;
TaskId bad = 0;
good = w.scheduler.schedule_once(1s, [&] { static_cast<void>(w.scheduler.cancel(good)); }).id;
bad = w.scheduler.schedule_once(1s, [&] {
static_cast<void>(w.scheduler.cancel(bad));
throw std::runtime_error("broke after cancel");
}).id;
w.advance(1s);
LLD_CHECK_EQ(w.info(good).state, TaskState::succeeded);
LLD_CHECK_EQ(w.info(bad).state, TaskState::failed);
LLD_CHECK_EQ(w.info(bad).error, std::string("broke after cancel"));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_4_7_a_finished_task_frees_its_callable_at_once_with_no_lock_held) {
World w;
// The destructor of this object calls the scheduler, which takes the scheduler's lock.
// Each lambda below holds the only copy of its shared_ptr (the test keeps a weak_ptr,
// which does not keep the object alive), so the destructor runs exactly when the scheduler
// destroys the callable. Were that done with the lock held, accepting() would lock a mutex
// its own thread already holds: undefined behaviour, in practice a hang that the test
// runner's time limit reports.
struct CallsBack {
Scheduler* scheduler;
~CallsBack() { static_cast<void>(scheduler->accepting()); }
};
auto ran = std::make_shared<CallsBack>(CallsBack{&w.scheduler});
auto cancelled = std::make_shared<CallsBack>(CallsBack{&w.scheduler});
const std::weak_ptr<CallsBack> ran_alive = ran;
const std::weak_ptr<CallsBack> cancelled_alive = cancelled;
static_cast<void>(w.scheduler.schedule_once(1s, [held = std::move(ran)] {}));
const TaskId id = w.scheduler.schedule_once(5s, [held = std::move(cancelled)] {}).id;
LLD_CHECK(!ran_alive.expired()); // the scheduler holds the only copy
LLD_CHECK_EQ(w.scheduler.cancel(id), CancelResult::cancelled);
LLD_CHECK(cancelled_alive.expired()); // cancel destroyed it before returning
w.advance(1s);
LLD_CHECK(ran_alive.expired()); // the worker destroyed it after the run
}

The point of AC-4.7 is who holds the last reference. Each lambda holds the only std::shared_ptr to its CallsBack, and the test keeps only a std::weak_ptr, which can tell whether the object still exists without keeping it alive. So the destructor that calls accepting() runs at the moment the scheduler destroys the callable, on the thread that does it. If that thread held the lock, accepting() would lock a mutex its own thread already holds; that is undefined behaviour, and in practice the test hangs until the runner’s 120-second limit reports it.

Shutdown (UC-6). The discard test needs a task that is still running when shutdown is called. This helper counts a latch down (so the test knows it started), then spins until shutdown begins:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
Task blocker(Scheduler& scheduler, std::latch& started) {
return [&scheduler, &started] {
started.count_down();
while (scheduler.accepting()) std::this_thread::yield();
};
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_6_1_discard_cancels_every_task_not_started_and_waits_for_the_running_one) {
World w;
std::latch started(1);
std::atomic<int> runs{0};
const TaskId busy = w.scheduler.schedule_once(0s, blocker(w.scheduler, started)).id;
started.wait();
const TaskId due = w.scheduler.schedule_once(1s, [&] { ++runs; }).id;
const TaskId later = w.scheduler.schedule_once(5s, [&] { ++runs; }).id;
const TaskId beat = w.scheduler.schedule_every(1s, 1s, [&] { ++runs; }).id;
w.clock.advance(1s); // `due` and `beat` are due, but the only worker is busy
w.scheduler.shutdown(ShutdownPolicy::discard);
LLD_CHECK_EQ(runs.load(), 0);
LLD_CHECK_EQ(w.info(busy).state, TaskState::succeeded); // it finished before shutdown returned
for (const TaskId id : {due, later, beat}) {
LLD_CHECK_EQ(w.info(id).state, TaskState::cancelled);
LLD_CHECK_EQ(w.info(id).reason, CancelReason::shutdown);
}
}
LLD_TEST(ac_6_2_drain_runs_the_tasks_already_due_and_cancels_the_later_ones) {
World w;
std::latch started(1);
Log log;
static_cast<void>(w.scheduler.schedule_once(0s, blocker(w.scheduler, started)));
started.wait();
const TaskId a = w.scheduler.schedule_once(1s, [&] { log.add("a"); }).id;
const TaskId b = w.scheduler.schedule_once(1s, [&] { log.add("b"); }).id;
const TaskId beat = w.scheduler.schedule_every(1s, 1s, [&] { log.add("beat"); }).id;
const TaskId later = w.scheduler.schedule_once(5s, [&] { log.add("later"); }).id;
w.clock.advance(1s);
w.scheduler.shutdown(ShutdownPolicy::drain);
LLD_CHECK_EQ(joined(log.lines()), std::string("a b beat"));
LLD_CHECK_EQ(w.info(a).state, TaskState::succeeded);
LLD_CHECK_EQ(w.info(b).state, TaskState::succeeded);
// The periodic task ran its due run once more and was then not rescheduled.
LLD_CHECK_EQ(w.info(beat).state, TaskState::cancelled);
LLD_CHECK_EQ(w.info(beat).reason, CancelReason::shutdown);
LLD_CHECK_EQ(w.info(beat).runs, 1);
LLD_CHECK_EQ(w.info(later).state, TaskState::cancelled);
LLD_CHECK_EQ(w.info(later).runs, 0);
}

Concurrency (groups 7 and 8). These tests cannot force a bad interleaving; they make one likely and check that whatever happened is consistent. The step 1 file also has the two tests of group 12, which do force one order. They are shown and explained with the step 2 tests, where they were first written, but what they test is step 1 code that step 2 did not change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_7_1_moving_the_clock_always_wakes_a_waiting_worker) {
// A lost wake-up would leave a due task unrun, and wait_until_idle would then never
// return (the test would hang and time out). Repeating it many times, with the clock moved
// while workers are deciding to sleep, gives a lost wake-up many chances to happen.
World w(2);
std::atomic<int> runs{0};
for (int i = 1; i <= 300; ++i) {
static_cast<void>(w.scheduler.schedule_once(1s, [&] { ++runs; }));
w.advance(1s);
LLD_CHECK_EQ(runs.load(), i);
}
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_8_3_a_cancel_racing_the_start_either_prevents_the_run_or_reports_it_running) {
for (int round = 0; round < 20; ++round) {
World w(4);
constexpr std::size_t tasks = 100;
std::vector<std::atomic<int>> runs(tasks);
std::vector<TaskId> ids;
for (std::size_t i = 0; i < tasks; ++i) {
std::atomic<int>& counter = runs[i];
ids.push_back(w.scheduler.schedule_once(1s, [&counter] { ++counter; }).id);
}
std::vector<CancelResult> answers(tasks, CancelResult::unknown_task);
std::latch go(3);
{
// One thread makes every task due while two others cancel the even-numbered ones.
std::jthread mover([&] {
go.arrive_and_wait();
w.clock.advance(1s);
});
std::jthread low([&] {
go.arrive_and_wait();
for (std::size_t i = 0; i < tasks / 2; i += 2) answers[i] = w.scheduler.cancel(ids[i]);
});
std::jthread high([&] {
go.arrive_and_wait();
for (std::size_t i = tasks / 2; i < tasks; i += 2)
answers[i] = w.scheduler.cancel(ids[i]);
});
}
w.scheduler.wait_until_idle();
bool consistent = true;
for (std::size_t i = 0; i < tasks; ++i) {
const TaskInfo info = w.info(ids[i]);
const int ran = runs[i].load();
if (i % 2 == 1 || answers[i] != CancelResult::cancelled) {
// Not cancelled in time: it ran exactly once and succeeded.
consistent = consistent && ran == 1 && info.state == TaskState::succeeded;
} else {
consistent = consistent && ran == 0 && info.state == TaskState::cancelled;
}
}
LLD_CHECK(consistent);
}
}
How this code works: What ac_8_3 checks, and what it cannot
  1. Set up. Four workers and 100 run-once tasks, all due at 1 second. Each task has its own std::atomic<int> counter.
  2. Start together. A std::latch of 3 holds three threads at the line: one moves the clock to 1 second, which makes every task due; two cancel the even-numbered tasks, one from each half.
  3. The std::jthreads join at the end of their block, so every cancel has returned before the test looks.
  4. Check each task. A task that was cancelled in time (CancelResult::cancelled) never ran and is cancelled. Every other task, odd or too late to cancel, ran exactly once and succeeded, even if cancel said running, because a run-once task keeps its result (AC-4.3).
  5. Twenty rounds, each with a fresh scheduler.

What it cannot do: say which interleavings happened. On a quiet machine every cancel might win, and the “running” branch might never be taken. The test is useful because it fails loudly if any interleaving is inconsistent, not because it proves every one was tried. See Testing concurrent code and its limits.

A test suite is only as good as the mistakes it catches. In the review of this page, seven mistakes were put into a scratch copy of step 1, one at a time, and the 40 tests were run against each (g++ 11.4, -O1, a 60-second limit per run, on 2026-11-28):

Mutant Result
next_slot plans from now, not from the planned time caught: 3 failed checks, in AC-3.1 and AC-3.2
next_slot never skips missed runs caught: 5 failed checks, in AC-3.2 and AC-3.3
drain keeps only tasks due strictly before the cutoff caught: 4 failed checks, in AC-6.2
a periodic task ignores cancel_requested caught: 5 failed checks, in AC-4.2 and AC-8.4
run_front destroys the callable with the lock held caught: hangs in AC-4.7
cancel declares doomed after the lock caught: hangs in AC-4.7
time_moved notifies without the lock caught: hangs in AC-12.1, in 5 runs out of 5

A hang is how a lock mistake shows here: the test cannot fail a check while its thread waits for itself. The runner prints only the file and line of a failed check, so for the table a copy of it was used that also prints each test’s name as it starts; that is how the hangs are placed. For the last mutant, three runs were made before that copy existed; they hung too, but did not name the test.

Two of these mistakes were not caught before the review. AC-4.7 used to keep its own std::shared_ptr to each CallsBack, so the scheduler’s copy was never the last one: destroying it only lowered a count, and the destructor that calls the scheduler ran at the end of the test, whatever the scheduler did. The test checked “freed at once” and not “with no lock held”. It now keeps only a std::weak_ptr. And step 1 had no forced-order test, so the lost wake-up went unseen in 5 runs of the suite: it needs the clock to move in a gap of a few instructions, and AC-7.1’s 300 tries did not hit it. Step 1 now has group 12 as well. The same lost-wake-up mutant in step 2 hung in 4 runs out of 4 (once with test names, in AC-12.1), and the callable mutant in step 2 hung in AC-4.7.

The code agent also reported a mutation check of step 2 while building the example, with 16 of 16 mutants killed; that check was not rerun for this page, and its list of mutants is not reproduced here.

Three months later:

“Two things. Half our jobs call a service that is down for a minute now and then, and a single failure marks them failed for good. Can a task try again, waiting a bit longer each time? And our nightly pipeline is fetch, then transform, then publish. Today we guess the delays so each one starts after the last has finished. Can a task wait for another task instead?”

New requirements.

  • FR-8 Retries. A task may have a RetryPolicy: up to a number of retries after failed runs, the first after first_backoff, each wait double the last, never more than max_backoff. Waits count from the failure. A success ends a run of failures. A cancel during a run, or shutdown, stops further retries.
  • FR-9 Dependencies. A run-once task may wait for other run-once tasks to succeed. Its delay counts from the moment the last one succeeds. If one of them fails for good or is cancelled, the waiting task is cancelled, with the reason and the dependency that caused it, and so is everything waiting for it in turn. A batch of tasks that depend on each other is scheduled all or nothing.

UC-9 Retry.

  • AC-9.1 A failing task is retried after 1, 2, and 4 seconds, then succeeds (runs at 1, 2, 4, and 8 seconds).
  • AC-9.2 After the last retry, a failure is final, and the error is kept.
  • AC-9.3 The wait stops growing at max_backoff (2, 4, 5, 5).
  • AC-9.4 A bad retry policy is refused and uses no id.
  • AC-9.5 A task waiting for its retry can be cancelled.
  • AC-9.6 A run that fails after cancel was called is not retried.
  • AC-9.7 A periodic task retries, then keeps its planned times.
  • AC-9.8 A failure during a drain is not retried.
  • AC-9.9 A retry not yet due at shutdown is cancelled.

UC-10 Wait for other tasks.

  • AC-10.1 A task waits for its dependency, and its delay counts from then.
  • AC-10.2 A dependency that has already succeeded is met at once.
  • AC-10.3 A task can wait for several dependencies.
  • AC-10.4 A final failure cancels the whole chain behind it, each with its reason and cause.
  • AC-10.5 Cancelling a dependency cancels its dependents.
  • AC-10.6 A waiting task can be cancelled, and its dependency still runs.
  • AC-10.7 A success on a retry releases the dependents.
  • AC-10.8 Unknown dependencies are refused.
  • AC-10.9 A batch with a cycle is refused whole.
  • AC-10.10 A periodic dependency is refused.
  • AC-10.11 A dependency that has already failed or been cancelled is refused.
  • AC-10.12 A batch may list a task before its dependency, and may form a diamond.
  • AC-10.13 Shutdown cancels waiting tasks, even if a dependency is drained.
  • AC-10.14 A periodic task can wait for a dependency.
  • AC-10.15 Dependents released together run in scheduling order.
  • AC-10.16 A dependency cancelled during a successful run still releases its dependents.
  • AC-10.17 A refused batch leaves no trace.
  • AC-10.18 A task cancelled by one dependency stays cancelled when another succeeds.
  • AC-10.19 schedule_once and schedule check the same rules.

UC-11 Dependencies under concurrency.

  • AC-11.1 Dependencies finishing at the same moment release a task once.
  • AC-11.2 One failure among concurrent dependencies cancels.
  • AC-11.3 A cancel racing a chain leaves a consistent result.
  • AC-11.4 Dependents scheduled while their dependency completes each run once.
  • AC-11.5 A chain 10,000 tasks long is cancelled without recursion.

UC-12 Races forced into their worst order.

  • AC-12.1 A clock move just before a worker sleeps still wakes it.
  • AC-12.2 Cancelling the due task before a worker takes it ends wait_until_idle.

AC-12.1 and AC-12.2 test step 1 code that did not change. They were written with step 2, and step 1’s tests now have them too, unchanged.

Part Step 1 Step 2
scheduling schedule_once, schedule_every call add both build a TaskSpec and go through schedule_all; schedule takes a TaskSpec
states five adds waiting: accepted, not yet in the queue
after a run four branches in run_front finish_run: retry, repeat, or a final state, and what that means for dependents
refusals four adds bad_retry, unknown_dependency, periodic_dependency, dependency_cycle, dependency_finished
cancel reasons by_request, shutdown adds dependency_failed and dependency_cancelled, with a cause
Record the task, state, runs, error, node adds the retry policy and count, failures, planned, unmet, dependents, cause, next_to_cancel
shutdown cancels what is not due also cancels every waiting task, under either policy
unchanged the queue, the clock, work, time_moved, wait_until_idle, the constructor the same

The worker loop, the clock, and the locking did not change at all. The change lives in two places: what happens after a run, and what happens at scheduling. That is the reward for having kept the run itself (unlock, call, catch, lock) separate from deciding what comes next.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

task.hpp
// A task is any callable that takes nothing and returns nothing. The scheduler keeps it in a
// std::function, which owns a copy of the callable (and so of everything a lambda captured).
// std::function needs a copyable callable; C++23's std::move_only_function would also take a
// move-only one, such as a lambda that captures a std::unique_ptr.
using Task = std::function<void()>;
// Each scheduled task gets a number, 1, 2, 3, ... in the order they were accepted.
// 0 means "no task".
using TaskId = std::uint64_t;
// Where a task is in its life:
// waiting not yet in the queue: some of its dependencies have not succeeded yet
// pending in the queue, waiting for its due time (a first run, a repeat, or a retry)
// running a worker is running it now
// succeeded a run-once task whose run returned normally (final)
// failed a run threw and no retry is left; the task never runs again (final)
// cancelled it will never run again; CancelReason says why (final)
// A periodic task goes pending -> running -> pending ... until it fails or is cancelled.
enum class TaskState { waiting, pending, running, succeeded, failed, cancelled };
// Why a task was cancelled. For the two dependency reasons, TaskInfo::cause names the
// dependency.
// dependency_failed a task it depends on failed for good
// dependency_cancelled a task it depends on was cancelled (for any reason but shutdown)
enum class CancelReason { none, by_request, shutdown, dependency_failed, dependency_cancelled };
// Why a schedule call refused. A refused task gets no id, and a refused batch schedules nothing.
// bad_retry a negative max_retries, or with retries, a backoff that is not
// positive or a max_backoff below first_backoff
// unknown_dependency no task has that id, or a batch index is out of range
// dependency_cycle the dependencies within a batch go round in a circle
// periodic_dependency a periodic task never finishes, so it cannot be waited for
// dependency_finished the dependency has already failed or been cancelled, so the new
// task could never run
enum class Refusal {
none,
shut_down,
empty_task,
negative_delay,
bad_period,
bad_retry,
unknown_dependency,
dependency_cycle,
periodic_dependency,
dependency_finished,
};
// What cancel did:
// cancelled the task was waiting or pending; it will never run, and the tasks
// waiting for it are cancelled too (dependency_cancelled)
// running a run is in progress. That run is not interrupted (a thread cannot be
// stopped safely from outside) and its result stands: a run-once task
// still ends succeeded or failed. The task never starts again: no
// repeat and no retry. A periodic task ends cancelled (or failed, if that
// last run threw).
// already_finished it had succeeded, failed, or been cancelled already; nothing changes
// unknown_task no task has that id
enum class CancelResult { cancelled, running, already_finished, unknown_task };
// What shutdown does with tasks that have not started:
// drain runs those already due when shutdown is called, and cancels the rest (later
// ones, retries not yet due, and every waiting task)
// discard cancels them all
// Either way it waits for running tasks to finish. Nothing is rescheduled or retried after
// shutdown begins.
enum class ShutdownPolicy { drain, discard };
// How a failed run is retried. After the k-th failure in a row (k <= max_retries), the task
// runs again first_backoff * 2^(k-1) after the failure, measured on the scheduler's clock,
// but never more than max_backoff after it. With the defaults below and max_retries = 3, the
// retries come 1, 2 and 4 seconds after each failure. The failure after the last retry is
// final. Waiting longer each time gives a struggling service room to recover, and the cap
// stops the wait from growing without limit.
struct RetryPolicy {
int max_retries = 0; // 0: a failure is final at once, as in step 1
Duration first_backoff = std::chrono::seconds{1};
Duration max_backoff = std::chrono::seconds{60};
};
// Everything about one task to schedule. The task becomes ready when every dependency has
// succeeded (at once if it has none); `delay` counts from that moment.
// after ids of tasks already scheduled
// after_spec positions of other specs in the same schedule_all call, so a batch can
// describe a whole graph of tasks before any of them has an id
struct TaskSpec {
Task task;
Duration delay{};
Duration period{}; // zero: run once
std::vector<TaskId> after;
std::vector<std::size_t> after_spec;
RetryPolicy retry;
};
// The answer to a schedule call: an id, or the reason it was refused.
struct Scheduled {
TaskId id = 0; // 0 when refused
Refusal refusal = Refusal::none;
[[nodiscard]] bool ok() const { return refusal == Refusal::none; }
};
// The answer to schedule_all: one id per spec, in order, or the first refusal found and the
// position of the spec it is about (and no ids).
struct Batch {
std::vector<TaskId> ids;
Refusal refusal = Refusal::none;
std::size_t spec = 0;
[[nodiscard]] bool ok() const { return refusal == Refusal::none; }
};
// A copy of what the scheduler knows about one task at the moment info() was called.
struct TaskInfo {
TaskState state = TaskState::pending;
int runs = 0; // how many times a worker has started it, retries included
int failures = 0; // how many of those runs threw
std::string error; // what the latest failed run threw (kept after a successful retry)
CancelReason reason = CancelReason::none;
TaskId cause = 0; // for the dependency reasons: the dependency that ended badly
};

after_spec is the piece that makes a pipeline possible in one call. A caller cannot name a task that has no id yet, so within a batch, tasks refer to each other by position. Batch::spec says which position was refused, so “dependency cycle at spec 0” points at the problem.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.hpp
// Everything about one task. Records live in a std::map by id and are never removed, so a
// Record& stays valid while the lock is released: a map never moves its elements.
//
// Who owns the callable: the record, except during a run, when the worker running it holds
// it. When a task will never run again, the worker (after the last run) or cancel destroys
// the callable with the lock released. Tasks cancelled by shutdown or because of a
// dependency keep theirs until the scheduler is destroyed.
//
// Everything a record will ever need is allocated when the task is scheduled, including its
// queue node and room in each dependency's `dependents`. After that, running, retrying,
// releasing and cancelling tasks never allocate, so they cannot fail half-way.
struct Record {
Task task;
Duration delay{}; // counts from the moment the task is ready
Duration period{}; // zero for a run-once task
RetryPolicy retry;
TaskState state = TaskState::pending;
int runs = 0;
int failures = 0;
int retries_used = 0; // failed runs since the last success
TimePoint planned; // periodic: the planned time of the current run
std::exception_ptr error; // what the latest failed run threw; null if none
CancelReason reason = CancelReason::none;
TaskId cause = 0; // the dependency behind a dependency reason
bool cancel_requested = false; // cancel() was called during a run
int unmet = 0; // dependencies that have not succeeded yet
std::vector<TaskId> dependents; // tasks that wait for this one
TaskId next_to_cancel = 0; // link in cancel_dependents' list; 0 ends it
Queue::node_type slot; // the task's queue node, kept here while not queued
Queue::iterator where; // its entry in queue_; valid only while pending
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// How long to wait before retry number `retry` (1 for the first): first_backoff, doubled for
// each earlier retry, but never more than max_backoff. It stops doubling at the cap, and
// doubles only values at most half the cap, so the multiplication cannot overflow.
Duration backoff(const RetryPolicy& policy, int retry) {
Duration wait = policy.first_backoff;
for (int i = 1; i < retry && wait < policy.max_backoff; ++i)
wait = wait > policy.max_backoff / 2 ? policy.max_backoff : wait * 2;
return std::min(wait, policy.max_backoff);
}
How this code works: backoff, on the demo's fetch and on AC-9.3

The demo’s fetch has max_retries 3, first_backoff 2 seconds, and max_backoff 60 seconds. It runs first at 1 second.

Failure at retries_used after it backoff(policy, retries_used) Next run
1s 1 2s (the loop does not run) 3s
3s 2 2s doubled once = 4s 7s

At 7 seconds fetch succeeds, so retries_used goes back to 0 and the third retry is never needed.

AC-9.3 uses max_retries 4, first_backoff 2 seconds, and max_backoff 5 seconds, which shows the cap:

Retry Loop steps Wait
1 none 2s
2 2s is not more than 5s / 2, so double: 4s 4s
3 4s, then 4s is more than 2.5s, so jump to the cap: 5s 5s
4 5s; the loop stops at once, because 5s is not below the cap 5s

So the runs come at 1, 3, 7, 12, and 17 seconds, and the failure at 17 is final. A wait is doubled only while it is at most half the cap, so wait * 2 can never be larger than max_backoff, and never overflow.

Exponential backoff is the usual shape for retries, because a service that is struggling recovers faster if its callers back off. Many systems add random jitter to each wait, so that many clients that failed together do not all retry at the same moment; this scheduler does not, because the team has one process and the tests want exact times. Retrying is only safe for a task that can run twice: Idempotency, retries, and duplicate handling is the page on that, and the scheduler cannot check it for the caller.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Decides what follows a run: a retry, the next periodic run, or a final state, and what that
// means for the tasks waiting for this one. Returns true if the task will run again. Nothing
// is retried or repeated once cancel was called during the run or shutdown has begun. The
// caller holds the lock.
bool Scheduler::finish_run(Record& rec, TaskId id, const std::exception_ptr& error) noexcept {
const TimePoint now = clock_.now();
const bool may_go_on = !rec.cancel_requested && phase_ == Phase::running;
if (error) {
rec.error = error;
++rec.failures;
if (may_go_on && rec.retries_used < rec.retry.max_retries) {
// A retry counts from the failure, not from the planned time: the point is to give
// whatever failed time to recover.
++rec.retries_used;
make_due(rec, id, now + backoff(rec.retry, rec.retries_used));
return true;
}
rec.state = TaskState::failed; // failed for good
cancel_dependents(id, CancelReason::dependency_failed);
return false;
}
rec.retries_used = 0; // a success ends a run of failures
if (rec.period == Duration::zero()) {
rec.state = TaskState::succeeded;
release_dependents(rec);
return false;
}
if (!may_go_on) {
// A periodic task has no dependents (refused at schedule time), so there is no one to
// tell.
rec.state = TaskState::cancelled;
rec.reason = rec.cancel_requested ? CancelReason::by_request : CancelReason::shutdown;
return false;
}
// The next run keeps the beat of the planned times, even if this run was a retry.
rec.planned = next_slot(rec.planned, rec.period, now);
make_due(rec, id, rec.planned);
return true;
}

finish_run replaces the four branches of step 1. Its first line decides whether anything may follow (may_go_on), so a cancel during the run and shutdown stop retries and repeats in the same way (AC-9.6, AC-9.8). A retry counts from the failure (now), not from the planned time, because its purpose is to give the failing service time. But a periodic task keeps planned, so after a retry that succeeds, its next run is back on the beat (AC-9.7).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Returns the position of a spec that is on a cycle of after_spec links, or waits for one,
// or nullopt if there is no cycle. This is Kahn's method: repeatedly take out a spec whose
// in-batch dependencies have all been taken out already. In a graph without cycles every spec
// is taken out in the end; the specs left over are on a cycle or behind one.
// Ids of tasks already scheduled cannot form a cycle: they can only point at older tasks.
std::optional<std::size_t> find_cycle(const std::vector<TaskSpec>& specs) {
const std::size_t count = specs.size();
std::vector<std::size_t> left(count); // in-batch dependencies not taken out
std::vector<std::vector<std::size_t>> users(count); // users[j]: the specs waiting for j
std::vector<std::size_t> ready; // specs with left == 0, to take out
for (std::size_t i = 0; i < count; ++i) {
left[i] = specs[i].after_spec.size();
for (const std::size_t j : specs[i].after_spec) users[j].push_back(i);
if (left[i] == 0) ready.push_back(i);
}
std::size_t taken = 0;
while (!ready.empty()) {
const std::size_t j = ready.back();
ready.pop_back();
++taken;
for (const std::size_t user : users[j])
if (--left[user] == 0) ready.push_back(user);
}
if (taken == count) return std::nullopt;
for (std::size_t i = 0; i < count; ++i)
if (left[i] != 0) return i;
return std::nullopt; // not reached: taken < count means some spec is left over
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// Accepts a batch of tasks, all or nothing, in four stages: checks that need no lock, checks
// against the scheduler's state, allocating everything, and then changing the scheduler's
// state with steps that cannot fail. So a refusal, or a std::bad_alloc while allocating,
// leaves the scheduler exactly as it was.
Batch Scheduler::schedule_all(std::vector<TaskSpec> specs) {
const std::size_t count = specs.size();
// 1. Checks that need no lock: each spec alone, then the links within the batch.
for (std::size_t i = 0; i < count; ++i) {
if (const Refusal refusal = check_alone(specs[i], count); refusal != Refusal::none)
return refused(refusal, i);
dedupe(specs[i].after);
dedupe(specs[i].after_spec);
}
for (std::size_t i = 0; i < count; ++i)
for (const std::size_t j : specs[i].after_spec)
if (specs[j].period != Duration::zero())
return refused(Refusal::periodic_dependency, i);
if (const std::optional<std::size_t> bad = find_cycle(specs))
return refused(Refusal::dependency_cycle, *bad);
// Allocations that need no lock: how many new dependents each existing task gets, and
// room for the ids to return.
std::map<TaskId, std::size_t> extra;
for (const TaskSpec& spec : specs)
for (const TaskId dependency : spec.after) ++extra[dependency];
Batch result;
result.ids.reserve(count);
std::lock_guard lock(mutex_);
// 2. Checks against the scheduler's state.
if (phase_ != Phase::running) return refused(Refusal::shut_down, 0);
for (std::size_t i = 0; i < count; ++i)
if (const Refusal refusal = check_existing(specs[i]); refusal != Refusal::none)
return refused(refusal, i);
// 3. Allocate everything else, still changing nothing anyone can see: the new records
// (in a map of their own, with their queue nodes and their in-batch dependents), and
// room in each existing dependency's list of dependents. reserve changes only capacity.
const TaskId first = next_id_;
std::map<TaskId, Record> fresh;
for (std::size_t i = 0; i < count; ++i)
fresh.try_emplace(first + i).first->second.slot = new_slot();
for (std::size_t i = 0; i < count; ++i)
for (const std::size_t j : specs[i].after_spec)
fresh.find(first + j)->second.dependents.push_back(first + i);
for (const auto& [dependency, more] : extra) {
std::vector<TaskId>& list = record(dependency).dependents;
list.reserve(list.size() + more);
}
// 4. Commit. Nothing below allocates or throws: swap, push_back into reserved room,
// and merge (which moves the nodes of `fresh` into records_ without copying them).
for (std::size_t i = 0; i < count; ++i) {
const TaskSpec& spec = specs[i];
Record& rec = fresh.find(first + i)->second;
rec.task.swap(specs[i].task);
rec.delay = spec.delay;
rec.period = spec.period;
rec.retry = spec.retry;
rec.unmet = static_cast<int>(spec.after_spec.size());
for (const TaskId dependency : spec.after) {
Record& dep = record(dependency);
if (dep.state == TaskState::succeeded) continue; // already met
dep.dependents.push_back(first + i);
++rec.unmet;
}
}
records_.merge(fresh);
next_id_ += count;
const TimePoint now = clock_.now();
for (std::size_t i = 0; i < count; ++i) {
Record& rec = record(first + i);
if (rec.unmet == 0) {
rec.planned = now + rec.delay;
make_due(rec, first + i, rec.planned);
} else {
rec.state = TaskState::waiting;
}
result.ids.push_back(first + i);
}
return result;
}
How this code works: schedule_all on the demo's pipeline

The demo’s first batch has three specs: fetch (spec 0, delay 1 second, the retry policy above), transform (spec 1, after_spec 0), and publish (spec 2, after_spec 1, delay 5 seconds).

  1. Checks with no lock. Each spec alone passes check_alone: a task, no negative delay or period, a valid retry policy, and every after_spec index below 3. No spec depends on a periodic spec. find_cycle starts with fetch ready (no in-batch dependencies), takes it, which makes transform ready, then publish: all three taken, no cycle.
  2. Checks under the lock. The scheduler is running, and no spec names an existing task in after, so check_existing has nothing to look up.
  3. Allocate. first is 1. Three records go into a separate map, fresh, each with its queue node. Transform is added to fetch’s dependents, and publish to transform’s. No existing record needs room.
  4. Commit. The callables are swapped in, unmet is 0 for fetch and 1 for the other two, and records_.merge(fresh) moves the three nodes into the main map without copying or allocating. Fetch is queued, due at 1 second; transform and publish are waiting. The ids returned are 1, 2, and 3.

The demo’s next batch has spec 0 after spec 1 and spec 1 after spec 0. In find_cycle, neither is ready at the start, so nothing is taken, and the first spec left over is 0: “dependency cycle at spec 0”. Then a task after task 42 fails check_existing: “unknown dependency”. Both are refused before anything changes in the scheduler, so they use no ids (AC-10.17). (In the demo they come after check and audit, which have already taken ids 4 and 5.)

The four stages are the same idea as add in step 1, at a larger scale: every check and every allocation before the first change that anyone can see. The last stage uses only operations that cannot throw: swap, push_back into room that reserve made, and std::map::merge, which moves nodes from one map into another. So a batch is either all scheduled or not at all, even if memory runs out half-way through stage 3 (AC-10.17). See Exception safety and failure atomicity.

The cycle check runs only within the batch. A task already scheduled can only depend on tasks older than itself, because a task’s dependencies must exist when it is scheduled, so a cycle through existing tasks is impossible.

Why refuse a periodic dependency? A periodic task never succeeds for good; it would be unclear whether the dependent runs after its first run, every run, or never. Refusing it is honest; guessing would be a bug report later.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// A run-once task has succeeded. Each task waiting for it now has one dependency fewer; one
// with none left is ready, and is queued `delay` from now. A task that is no longer waiting
// (it was cancelled meanwhile) is skipped. Several dependencies can finish at the same moment
// on different workers, but each finish runs here under the lock, one after another, so the
// count reaches zero exactly once. The caller holds the lock.
void Scheduler::release_dependents(const Record& rec) noexcept {
const TimePoint now = clock_.now();
for (const TaskId user_id : rec.dependents) {
Record& user = record(user_id);
if (user.state != TaskState::waiting) continue;
if (--user.unmet == 0) {
user.planned = now + user.delay;
make_due(user, user_id, user.planned);
}
}
}

release_dependents is short because the lock does the hard part. Two dependencies can succeed at the same moment on two workers, but each finish_run holds the lock, so the two decrements of unmet happen one after the other, and exactly one of them sees zero (AC-11.1).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
// `root` has failed for good or been cancelled, so every task waiting for it, directly or
// through other waiting tasks, can never run: cancel them all. The first ring gets `reason`
// (dependency_failed or dependency_cancelled), those further out dependency_cancelled, and
// each records as `cause` the dependency that ended it.
//
// It must not allocate (it runs inside a worker, where a std::bad_alloc could not be
// reported), and it must not recurse (a chain of 100,000 tasks would overflow the stack). So
// the list of tasks still to visit is threaded through the records themselves: each holds the
// id of the next one in next_to_cancel, and `todo` is the head of the list. A task is marked
// cancelled when it is added, so it is never added twice. The caller holds the lock.
void Scheduler::cancel_dependents(TaskId root, CancelReason reason) noexcept {
TaskId todo = 0; // 0: the list is empty
auto cancel_users_of = [&](TaskId ended, CancelReason why) {
for (const TaskId user_id : record(ended).dependents) {
Record& user = record(user_id);
if (user.state != TaskState::waiting) continue; // already cancelled
user.state = TaskState::cancelled;
user.reason = why;
user.cause = ended;
user.next_to_cancel = todo; // push onto the front of the list
todo = user_id;
}
};
cancel_users_of(root, reason);
while (todo != 0) {
const TaskId next = todo;
todo = record(next).next_to_cancel; // pop the front
cancel_users_of(next, CancelReason::dependency_cancelled);
}
}
How this code works: cancel_dependents on the chain in AC-10.4

AC-10.4 schedules a chain: task 2 after task 1, task 3 after task 2, task 4 after task 3. Task 1 fails for good, and finish_run calls cancel_dependents(1, dependency_failed). Read from the code:

Step Cancelled now todo after
cancel_users_of(1, failed) task 2: dependency_failed, cause 1, link 0 2
pop 2, cancel_users_of(2) task 3: dependency_cancelled, cause 2, link 0 3
pop 3, cancel_users_of(3) task 4: dependency_cancelled, cause 3, link 0 4
pop 4, cancel_users_of(4) nobody: task 4 has no dependents 0, done

The list of tasks still to visit lives in the records’ next_to_cancel fields, so the function allocates nothing. It is a loop, not a recursion, so a chain 10,000 long (AC-11.5) uses no more stack than a chain of two. A task is marked cancelled when it is put on the list, and the waiting check skips it after that, so a diamond cannot put a task on the list twice.

Why not a std::vector of ids to visit, or a recursive call? Both are simpler to read. But cancel_dependents runs inside finish_run, inside a worker, where there is nobody to report a std::bad_alloc to, so it must not allocate; and a chain as long as the caller likes would overflow the stack under recursion. An intrusive list (the link stored in the element itself) answers both.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
CancelResult Scheduler::cancel(TaskId id) {
// Declared before the lock, so it is destroyed after the lock is released (locals are
// destroyed in reverse order). It receives the callable of a task cancelled here.
Task doomed;
std::lock_guard lock(mutex_);
const auto found = records_.find(id);
if (found == records_.end()) return CancelResult::unknown_task;
Record& rec = found->second;
switch (rec.state) {
case TaskState::waiting:
case TaskState::pending:
if (rec.state == TaskState::pending) {
rec.slot = queue_.extract(rec.where); // out of the queue; it keeps its node
}
rec.state = TaskState::cancelled;
rec.reason = CancelReason::by_request;
doomed.swap(rec.task);
cancel_dependents(id, CancelReason::dependency_cancelled);
changed_.notify_all(); // a due task may have left the queue: we may be idle now
return CancelResult::cancelled;
case TaskState::running:
// The worker reads this flag when the run ends; see CancelResult::running.
rec.cancel_requested = true;
return CancelResult::running;
case TaskState::succeeded:
case TaskState::failed:
case TaskState::cancelled:
return CancelResult::already_finished;
}
return CancelResult::already_finished; // not reached: the switch covers every state
}

Cancel now handles waiting as well as pending, and spreads the cancel to the task’s dependents with dependency_cancelled.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

scheduler.cpp
void Scheduler::shutdown(ShutdownPolicy policy) {
if (on_worker_thread()) throw std::logic_error("shutdown called from a task");
std::unique_lock lock(mutex_);
if (phase_ != Phase::running) {
// Another thread has begun the shutdown, or it is done: wait until it is done.
changed_.wait(lock, [this] { return phase_ == Phase::stopped; });
return;
}
phase_ = Phase::stopping; // from here on, schedule refuses and nothing is rescheduled
// Take out of the queue every task that must not run: all of them for discard, and for
// drain those not yet due at this moment. With a manual clock, waiting for a later task
// could wait forever. What stays in the queue is due, so the workers run it and then end.
const TimePoint cutoff = clock_.now();
for (auto it = queue_.begin(); it != queue_.end();) {
if (policy == ShutdownPolicy::drain && it->due <= cutoff) {
++it;
continue;
}
Record& rec = record(it->id);
const auto after = std::next(it); // extract invalidates `it` only
rec.slot = queue_.extract(it);
rec.state = TaskState::cancelled;
rec.reason = CancelReason::shutdown;
it = after;
}
// Waiting tasks are not due, so they are cancelled under either policy. A dependency that
// succeeds during the drain therefore releases no one.
for (auto& entry : records_) {
Record& rec = entry.second;
if (rec.state != TaskState::waiting) continue;
rec.state = TaskState::cancelled;
rec.reason = CancelReason::shutdown;
}
wake_.notify_all(); // sleeping workers wake, run what is left, and end
changed_.notify_all(); // tasks left the queue
// Join with the lock released: the workers need it to finish. Only the thread that moved
// phase_ to stopping gets here, so no thread is joined twice.
lock.unlock();
for (std::jthread& worker : threads_) worker.join();
lock.lock();
phase_ = Phase::stopped;
changed_.notify_all(); // release any second caller of shutdown
}

The one new rule in shutdown: every waiting task is cancelled, under either policy. Finding them means a walk over every record the scheduler has ever had, with the lock held, because records are never erased; for a long-lived scheduler that walk grows without limit. A waiting task is not due, so drain would not run it anyway; and if a drained dependency succeeded during the drain, it would release a task that the scheduler is about to stop. Cancelling them first means a drain releases nobody (AC-10.13).

The states of one task in step 2
Text description of the diagram

A task starts waiting if some dependency has not yet succeeded, and pending otherwise. A waiting task becomes pending when its last dependency succeeds, and is cancelled if it is cancelled, if a dependency fails for good or is cancelled, or by shutdown. A pending task becomes running when it is due and a worker takes it, or is cancelled by cancel or shutdown. From running, a periodic task whose run ended goes back to pending, and so does a task that failed with a retry left, queued for after its backoff. A run-once task whose run returned succeeds. A task that threw with no retry left, or whose retries were stopped by cancel or shutdown, fails. A periodic task cancelled during its run, or whose run ended after shutdown began, is cancelled. Succeeded, failed, and cancelled are final.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> waiting : accepted, a dependency has not succeeded
[*] --> pending : accepted, nothing to wait for
waiting --> pending : the last dependency succeeded
waiting --> cancelled : cancel, a dependency failed or was cancelled, or shutdown
pending --> running : due, a worker takes it
pending --> cancelled : cancel, or shutdown
running --> pending : periodic run ended, or a retry is due later
running --> succeeded : run-once, run returned
running --> failed : threw, no retry left, or cancel or shutdown stopped retries
running --> cancelled : periodic, cancel during the run or shutdown
succeeded --> [*]
failed --> [*]
cancelled --> [*]

The 73 step 2 tests repeat step 1’s 38 tests of groups 1 to 8 and add groups 9 to 12 (group 12 is in step 1 too). Their helpers write a run as text: F@3 is a failed run at 3 seconds, ok@8 a successful one, and A@5 task A run at 5 seconds.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_9_1_retries_wait_a_doubling_backoff_measured_from_each_failure) {
World w;
Log log;
TaskSpec spec = make_spec(fails_first(w, log, 3), 1s);
spec.retry = retries(3, 1s, 60s);
const TaskId id = w.scheduler.schedule(std::move(spec)).id;
// Failures at 1, 2 and 4; retries 1, 2 and 4 seconds after them.
for (int step = 0; step < 8; ++step) w.advance(1s);
LLD_CHECK_EQ(joined(log.lines()), std::string("F@1 F@2 F@4 ok@8"));
const TaskInfo info = w.info(id);
LLD_CHECK_EQ(info.state, TaskState::succeeded);
LLD_CHECK_EQ(info.runs, 4);
LLD_CHECK_EQ(info.failures, 3);
LLD_CHECK_EQ(info.error, std::string("failure 3")); // the latest failure is kept
}
LLD_TEST(ac_9_2_the_failure_after_the_last_retry_is_final_and_recorded) {
World w;
Log log;
TaskSpec spec = make_spec(fails_first(w, log, 100), 1s);
spec.retry = retries(2, 1s, 60s);
const TaskId id = w.scheduler.schedule(std::move(spec)).id;
for (int step = 0; step < 4; ++step) w.advance(1s);
w.advance(100s);
LLD_CHECK_EQ(joined(log.lines()), std::string("F@1 F@2 F@4"));
const TaskInfo info = w.info(id);
LLD_CHECK_EQ(info.state, TaskState::failed);
LLD_CHECK_EQ(info.runs, 3);
LLD_CHECK_EQ(info.failures, 3);
LLD_CHECK_EQ(info.error, std::string("failure 3"));
}
LLD_TEST(ac_9_3_the_backoff_never_exceeds_max_backoff) {
World w;
Log log;
TaskSpec spec = make_spec(fails_first(w, log, 100), 1s);
spec.retry = retries(4, 2s, 5s); // waits 2, 4, then 5, 5 (8 and 16 capped)
const TaskId id = w.scheduler.schedule(std::move(spec)).id;
for (int step = 0; step < 20; ++step) w.advance(1s);
LLD_CHECK_EQ(joined(log.lines()), std::string("F@1 F@3 F@7 F@12 F@17"));
LLD_CHECK_EQ(w.info(id).state, TaskState::failed);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_10_4_a_final_failure_cancels_every_task_behind_it_with_reason_and_cause) {
World w;
Log log;
std::vector<TaskSpec> specs;
specs.push_back(make_spec([] { throw std::runtime_error("bad input"); }, 1s));
for (std::size_t i = 1; i < 4; ++i) {
specs.push_back(make_spec(named(log, "dependent")));
specs.back().after_spec = {i - 1};
}
const Batch batch = w.scheduler.schedule_all(std::move(specs));
LLD_CHECK(batch.ok());
w.advance(1s);
w.advance(10s);
LLD_CHECK(log.lines().empty());
const TaskInfo first = w.info(batch.ids[1]);
LLD_CHECK_EQ(first.state, TaskState::cancelled);
LLD_CHECK_EQ(first.reason, CancelReason::dependency_failed);
LLD_CHECK_EQ(first.cause, batch.ids[0]);
for (std::size_t i = 2; i < 4; ++i) {
const TaskInfo info = w.info(batch.ids[i]);
LLD_CHECK_EQ(info.state, TaskState::cancelled);
LLD_CHECK_EQ(info.reason, CancelReason::dependency_cancelled);
LLD_CHECK_EQ(info.cause, batch.ids[i - 1]);
LLD_CHECK_EQ(info.runs, 0);
}
}
LLD_TEST(ac_10_5_cancelling_a_dependency_cancels_its_dependents) {
World w;
Log log;
const TaskId a = w.scheduler.schedule_once(1s, named(log, "A")).id;
TaskSpec spec = make_spec(named(log, "B"));
spec.after = {a};
const TaskId b = w.scheduler.schedule(std::move(spec)).id;
LLD_CHECK_EQ(w.scheduler.cancel(a), CancelResult::cancelled);
w.advance(5s);
LLD_CHECK(log.lines().empty());
const TaskInfo info = w.info(b);
LLD_CHECK_EQ(info.state, TaskState::cancelled);
LLD_CHECK_EQ(info.reason, CancelReason::dependency_cancelled);
LLD_CHECK_EQ(info.cause, a);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_10_9_a_batch_with_a_cycle_is_refused_whole) {
World w;
std::atomic<int> runs{0};
const auto batch_of = [&runs](std::vector<std::vector<std::size_t>> links) {
std::vector<TaskSpec> specs;
for (auto& link : links) {
specs.push_back(make_spec([&runs] { ++runs; }));
specs.back().after_spec = std::move(link);
}
return specs;
};
const Batch self = w.scheduler.schedule_all(batch_of({{0}}));
LLD_CHECK_EQ(self.refusal, Refusal::dependency_cycle);
const Batch pair = w.scheduler.schedule_all(batch_of({{}, {2}, {1}}));
LLD_CHECK_EQ(pair.refusal, Refusal::dependency_cycle);
LLD_CHECK_EQ(pair.spec, std::size_t{1});
// 1 -> 3 -> 2 -> 1, and 4 waits behind the cycle; 0 is fine on its own.
const Batch ring = w.scheduler.schedule_all(batch_of({{}, {3}, {1}, {2}, {1}}));
LLD_CHECK_EQ(ring.refusal, Refusal::dependency_cycle);
LLD_CHECK_EQ(ring.spec, std::size_t{1});
LLD_CHECK(ring.ids.empty());
w.advance(5s);
LLD_CHECK_EQ(runs.load(), 0);
LLD_CHECK(!w.scheduler.info(1).has_value());
LLD_CHECK_EQ(w.scheduler.schedule_once(1s, [] {}).id, TaskId{1});
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_11_5_a_failure_at_the_head_of_a_long_chain_cancels_it_all_without_recursion) {
World w(2);
constexpr std::size_t length = 10000;
std::atomic<int> runs{0};
std::vector<TaskSpec> specs;
specs.push_back(make_spec([] { throw std::runtime_error("head failed"); }, 1s));
for (std::size_t i = 1; i < length; ++i) {
specs.push_back(make_spec([&runs] { ++runs; }));
specs.back().after_spec = {i - 1};
}
const Batch batch = w.scheduler.schedule_all(std::move(specs));
LLD_CHECK(batch.ok());
w.advance(1s);
LLD_CHECK_EQ(runs.load(), 0);
const TaskInfo tail = w.info(batch.ids.back());
LLD_CHECK_EQ(tail.state, TaskState::cancelled);
LLD_CHECK_EQ(tail.reason, CancelReason::dependency_cancelled);
LLD_CHECK_EQ(tail.cause, batch.ids[length - 2]);
}

Group 12 is different. Instead of making a bad order likely, it forces it, with a clock built for the purpose:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
class HookClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override {
if (watched_ != std::thread::id{} && watched_ == std::this_thread::get_id() &&
!seen_now_.exchange(true))
on_now_->count_down();
return inner_.now();
}
void wait_until(std::unique_lock<std::mutex>& lock, std::condition_variable& wake,
TimePoint deadline) const override {
if (stall_.exchange(false)) {
// Hold the scheduler's lock, as a worker does between reading the time and
// sleeping, until the test says go or a bounded number of turns have passed (with
// a correct scheduler, advance cannot finish while this holds the lock).
stalled_->count_down();
for (int turn = 0; turn < 100000 && !go_; ++turn) std::this_thread::yield();
}
inner_.wait_until(lock, wake, deadline);
if (pause_.exchange(false)) {
// Just woken: let go of the lock, and wait for the test, before looking at the queue.
lock.unlock();
paused_->count_down();
resume_->wait();
lock.lock();
}
}
[[nodiscard]] std::uint64_t add_waker(Waker waker) override {
return inner_.add_waker(std::move(waker));
}
void remove_waker(std::uint64_t id) noexcept override { inner_.remove_waker(id); }
void advance(Duration step) { inner_.advance(step); }
// The next wait_until holds the lock before sleeping, and counts down `stalled`.
void stall_next_wait(std::latch& stalled) {
stalled_ = &stalled;
stall_ = true;
}
void go() { go_ = true; }
// The next wait_until, once woken, releases the lock, counts down `paused`, and waits
// for `resume`.
void pause_after_next_wake(std::latch& paused, std::latch& resume) {
paused_ = &paused;
resume_ = &resume;
pause_ = true;
}
// The first now() called on `thread` counts down `called`.
void watch_now(std::thread::id thread, std::latch& called) {
on_now_ = &called;
watched_ = thread;
}
private:
ManualClock inner_;
// The pointers are set before the flag that publishes them (atomic, so the worker that
// sees the flag sees the pointer too).
mutable std::atomic<bool> stall_{false};
std::latch* stalled_ = nullptr;
std::atomic<bool> go_{false};
mutable std::atomic<bool> pause_{false};
std::latch* paused_ = nullptr;
std::latch* resume_ = nullptr;
std::latch* on_now_ = nullptr;
std::atomic<std::thread::id> watched_{};
mutable std::atomic<bool> seen_now_{false};
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_12_1_a_clock_move_just_before_a_worker_sleeps_still_wakes_it) {
HookClock clock;
Scheduler scheduler(clock, 1);
std::latch stalled(1);
clock.stall_next_wait(stalled);
std::atomic<int> runs{0};
(void)scheduler.schedule_once(1s, [&runs] { ++runs; });
stalled.wait(); // the worker has seen "not due yet" and holds the lock
clock.advance(1s); // time_moved needs that lock, so it notifies only once the worker sleeps
clock.go();
scheduler.wait_until_idle(); // with the notify lost, this would never return
LLD_CHECK_EQ(runs.load(), 1);
}
LLD_TEST(ac_12_2_cancelling_the_due_task_before_a_worker_takes_it_ends_wait_until_idle) {
HookClock clock;
Scheduler scheduler(clock, 1);
// First make sure the worker is in wait_until: if the clock moved before that, the worker
// would find the task due and run it without ever sleeping.
std::latch stalled(1);
clock.stall_next_wait(stalled);
std::atomic<int> runs{0};
const TaskId id = scheduler.schedule_once(1s, [&runs] { ++runs; }).id;
stalled.wait();
std::latch paused(1);
std::latch resume(1);
clock.pause_after_next_wake(paused, resume);
clock.go();
clock.advance(1s);
paused.wait(); // the task is due, no task is running, and the worker is held off the lock
std::latch checked(1);
clock.watch_now(std::this_thread::get_id(), checked);
CancelResult answer = CancelResult::unknown_task;
std::jthread canceller([&] {
// wait_until_idle reads the time while it checks, with the lock held, and then sleeps.
// So this cancel gets the lock only once that wait is asleep, and must wake it.
checked.wait();
answer = scheduler.cancel(id);
resume.count_down();
});
scheduler.wait_until_idle();
canceller.join();
LLD_CHECK_EQ(answer, CancelResult::cancelled);
LLD_CHECK_EQ(runs.load(), 0);
const TaskInfo info = scheduler.info(id).value();
LLD_CHECK_EQ(info.state, TaskState::cancelled);
}
How this code works: How the two forced-order tests work, and where they stop

AC-12.1, the lost wake-up.

  1. The worker sees the task is not due and calls wait_until. The HookClock stalls it there, still holding the scheduler’s lock, which is the dangerous gap between reading the time and sleeping. The latch stalled tells the test it has got there.
  2. The test calls advance. With a correct scheduler, time_moved needs the lock, so advance cannot finish until the worker lets go. The worker spins for up to 100,000 turns of yield (the test calls go() only after advance, so with a correct scheduler all 100,000 turns run), then sleeps, releasing the lock; time_moved gets it, and the notify reaches a sleeping worker.
  3. With the lock taken out of time_moved (the mutant), advance returns at once, its notify goes to nobody, go() ends the spin, and the worker sleeps with a due task. wait_until_idle never returns.

The limit: the test catches the mutant only if advance finishes before the spin of 100,000 turns runs out. On a very slow or very busy machine the spin could end first, the worker would be asleep when the notify came, and the mutant would pass that run. In the review, a scratch copy of each step with the mutant hung in every run (5 of 5 for step 1, 4 of 4 for step 2, each stopped by a 60-second limit), and in the three runs that printed each test’s name as it started, the hang was in AC-12.1.

AC-12.2, a cancel that must wake wait_until_idle.

  1. As before, the worker is stalled in wait_until. Then the test asks the clock to hold the worker after it next wakes, with the lock released, and moves the clock. The task is due, nothing is running, and the worker cannot take it: so wait_until_idle will sleep.
  2. watch_now makes the clock count down a latch the first time the main thread asks for the time. wait_until_idle asks for the time inside idle(), under the lock, just before it sleeps. The canceller thread waits for that latch, then calls cancel, which needs the lock, so it runs only once wait_until_idle is asleep.
  3. cancel takes the task out of the queue and notifies changed_. wait_until_idle wakes, finds nothing due, and returns.

The limits: without the notify in cancel the test hangs rather than fails, as AC-12.1 does, and it is the test runner’s time limit (120 seconds per test program in cmake/LldExample.cmake) that turns the hang into a failure. And the test depends on idle() calling now(); an idle() written another way would make the latch never count down.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
ManualClock clock;
Scheduler scheduler(clock, 1);
auto say = [&clock](const std::string& what) {
std::cout << " t=" << seconds_of(clock.now()) << "s " << what << "\n";
};
auto advance_to = [&](seconds when) {
// Print first: once the clock moves, the worker may print at once.
std::cout << "clock at " << when.count() << "s\n";
clock.advance(when - duration_cast<seconds>(clock.now().time_since_epoch()));
scheduler.wait_until_idle();
};
// The pipeline, as one batch: transform waits for fetch (position 0), publish for
// transform (position 1), and publish waits 5s more once transform is done.
auto attempts = std::make_shared<int>(0); // only the worker running fetch touches it
std::vector<TaskSpec> pipeline;
pipeline.push_back(spec_of([&say, attempts] {
if (++*attempts <= 2) {
say("fetch: failed, network down");
throw std::runtime_error("network down");
}
say("fetch: done");
}, 1s));
pipeline[0].retry.max_retries = 3; // retries 2s, 4s, 8s after a failure
pipeline[0].retry.first_backoff = 2s;
pipeline.push_back(spec_of([&] { say("transform: done"); }, 0s));
pipeline[1].after_spec = {0};
pipeline.push_back(spec_of([&] { say("publish: done"); }, 5s));
pipeline[2].after_spec = {1};
const Batch batch = scheduler.schedule_all(std::move(pipeline));
const TaskId fetch = batch.ids[0];
const TaskId transform = batch.ids[1];
const TaskId publish = batch.ids[2];
// A check with no retries, and an audit that waits for it.
const TaskId check = scheduler.schedule_once(2s, [&] {
say("check: failed, bad checksum");
throw std::runtime_error("bad checksum");
}).id;
TaskSpec audit_spec = spec_of([&] { say("audit: done"); }, 0s);
audit_spec.after = {check};
const TaskId audit = scheduler.schedule(std::move(audit_spec)).id;
std::cout << "scheduled fetch, transform, publish (one batch), check, audit\n";
// Two batches that are refused whole: a cycle, and an unknown dependency.
std::vector<TaskSpec> circle;
circle.push_back(spec_of([] {}, 0s));
circle.push_back(spec_of([] {}, 0s));
circle[0].after_spec = {1};
circle[1].after_spec = {0};
const Batch cycle = scheduler.schedule_all(std::move(circle));
std::cout << "batch with a cycle: refused, " << to_string(cycle.refusal) << " at spec "
<< cycle.spec << "\n";
TaskSpec orphan = spec_of([] {}, 0s);
orphan.after = {42};
std::cout << "task after task 42: refused, "
<< to_string(scheduler.schedule(std::move(orphan)).refusal) << "\n";
show(scheduler, transform, "transform");
advance_to(1s); // fetch fails; retry at 3s
advance_to(2s); // check fails for good; audit is cancelled
advance_to(3s); // fetch fails again; retry at 7s
show(scheduler, fetch, "fetch");
advance_to(7s); // fetch succeeds, transform runs at once, publish is due at 12s
advance_to(12s);
std::cout << "shutdown (drain)\n";
scheduler.shutdown(ShutdownPolicy::drain);
std::cout << "final states:\n";
show(scheduler, fetch, "fetch");
show(scheduler, transform, "transform");
show(scheduler, publish, "publish");
show(scheduler, check, "check");
show(scheduler, audit, "audit");
}
Expected output
scheduled fetch, transform, publish (one batch), check, audit
batch with a cycle: refused, dependency cycle at spec 0
task after task 42: refused, unknown dependency
transform (task 2): waiting, runs 0, failures 0
clock at 1s
t=1s fetch: failed, network down
clock at 2s
t=2s check: failed, bad checksum
clock at 3s
t=3s fetch: failed, network down
fetch (task 1): pending, runs 2, failures 2, last error "network down"
clock at 7s
t=7s fetch: done
t=7s transform: done
clock at 12s
t=12s publish: done
shutdown (drain)
final states:
fetch (task 1): succeeded, runs 3, failures 2, last error "network down"
transform (task 2): succeeded, runs 1, failures 0
publish (task 3): succeeded, runs 1, failures 0
check (task 4): failed, runs 1, failures 1, last error "bad checksum"
audit (task 5): cancelled, runs 0, failures 0, reason dependency failed (task 4)

How to read it:

  • Scheduling. The pipeline batch gives ids 1 to 3, as the walkthrough above traced. Check (task 4, at 2 seconds, no retries) and audit (task 5, after check) follow. The cycle batch and the task after an unknown task are refused and use no ids. Transform is waiting.
  • At 1 second, fetch fails, and is queued again for 3 seconds.
  • At 2 seconds, check fails with no retries, so it is failed for good and audit is cancelled, dependency failed (task 4).
  • At 3 seconds, fetch fails again. It is pending, runs 2, failures 2, waiting until 7 seconds (backoff 4).
  • At 7 seconds, fetch succeeds, which releases transform (delay 0), which runs at once at 7 seconds and releases publish, due 5 seconds later.
  • At 12 seconds, publish runs.
  • Final states. Fetch succeeded on its third run and still shows its last error: failures and error are history, not a sign that it failed.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
0 to 5 Ask the questions that change the design: fixed rate or fixed delay, overlap, cancel during a run, shutdown, tests. “Every ten minutes from the start or from the finish? The answer changes one line, but it is the line people notice.”
5 to 10 Write FR and NFR; name the two that shape the code: no lock during a task, no real time in tests. “A task may call the scheduler, so it must run with the lock released.”
10 to 20 Sketch the queue (a set by due time and sequence), the record, the worker loop. “A set, not a priority queue, because cancel removes from the middle.”
20 to 30 Walk one run: take out under the lock, unlock, run, catch, lock, decide. “Between unlock and lock, the state running is what protects the task.”
30 to 38 Shutdown and the clock: phases, the drain cutoff, joining, the waker taking the lock. “Notify after passing through the lock, or the wake-up can be lost.”
38 to 45 Tests and limits: a manual clock, one forced race, what is not handled. “These tests make races likely; two of them force one order. Neither proves there are none.”
Level Usually expected
Junior A queue ordered by time; a worker thread that sleeps on a condition variable; run-once and periodic tasks; a flag to stop; a few tests.
Mid-level All of the above, plus: no lock while a task runs; a fixed rate that skips missed runs; cancel by id with an honest answer for a running task; exceptions caught per run; join on shutdown; an injected clock.
Senior All of the above, plus: the lost wake-up and why the waker takes the lock; drain and discard with a cutoff that cannot wait forever; callables destroyed outside the lock; no allocation after acceptance; how to test races and what such tests cannot show.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

Questions an interviewer may ask.

  • Why not one std::thread per task, sleeping until its time? That is the team’s old design: one thread per timer, and no bound on the number of threads. A pool shares a few threads among all tasks.
  • What happens if a task takes longer than its period? It never overlaps itself; the runs it missed are skipped, and the next run is the first planned time after it ends.
  • Can you stop a task that is running? Not safely from outside. The scheduler can promise only that it will not start again. A task that must stop early has to check a flag or a std::stop_token itself, which is cooperative cancellation.
  • What if the system clock jumps? The scheduler uses std::chrono::steady_clock, which does not jump when someone changes the wall-clock time. “Every day at nine” needs the wall clock and a calendar, which is out of scope.
  • Why does wait_until_idle exist? Isn’t it only for tests? Yes, and that is why it refuses to run from a task. It replaces “sleep and hope” with a condition the scheduler can check exactly.
  • No overflow check on due times. now + delay, planned + period, and now + backoff are computed without a guard. A delay close to Duration::max() overflows a signed integer, which is undefined behaviour. A production version would refuse delays beyond a limit or saturate the sum.
  • One process, all in memory. Tasks are lost when the process ends. There is no persistence, and no coordination between processes or machines, so two copies of the service each run every task.
  • No fairness and no priorities. Due time is the only order. A burst of tasks due now delays a later one; a task that blocks keeps a worker for as long as it blocks, and the pool does not grow.
  • No bound on the queue. Scheduling never pushes back; see Backpressure and bounded queues.
  • Records are never erased. Each finished task keeps its record and its queue node for the life of the scheduler, so a long-running service that schedules millions of tasks needs a way to forget old ones (for example, a record erased once its info has been read, or after a time).
  • Callables of tasks cancelled by shutdown (and, in step 2, of tasks cancelled because of a dependency) are destroyed only with the scheduler, not when they are cancelled. They are destroyed as the scheduler’s members are, so a destructor of one that calls the scheduler (as AC-4.7’s does) would use a half-destroyed object, which is undefined behaviour. NFR-2 holds (no lock is held then), but such callables must not call back.
  • Some steps hold the lock for long. shutdown walks the queue (and in step 2 every record), and a cancel that spreads down a chain of dependents visits all of them, with the lock held.
  • std::function needs a copyable callable. C++23’s std::move_only_function would remove that limit.
  • No jitter on retries, and no limit on retries across many tasks at once.
  • The forced-order tests have limits of their own: AC-12.1 depends on a spin of 100,000 turns outlasting advance, AC-12.2 on idle() calling now(), and both turn a bug into a hang that only the test runner’s time limit reports.
  • Observability. There are no metrics (queue length, lateness, run time) and no logging of failures beyond the stored text; see Observability.

See traceability.

Requirement Design element Code Tests Status
FR-1 run once add, make_due, work, run_front step 1 scheduler.cpp ac_1_1_…, ac_1_2_… Tested
FR-2 periodic next_slot, the repeat branch of run_front step 1 scheduler.cpp ac_1_3_…, ac_3_1_… to ac_3_3_… Tested
FR-3 order QueueKey, std::set step 1 scheduler.hpp ac_2_1_…, ac_2_2_… Tested
FR-4 cancel cancel, cancel_requested step 1 scheduler.cpp ac_4_1_… to ac_4_6_…, ac_8_3_…, ac_8_4_… Tested
FR-5 failures try/catch in run_front, message_of step 1 scheduler.cpp ac_5_1_… to ac_5_4_… Tested
FR-6 shutdown Phase, shutdown, the destructor step 1 scheduler.* ac_6_1_… to ac_6_7_…, ac_8_5_… Tested
FR-7 status TaskInfo, info step 1 task.hpp, scheduler.cpp used by most tests Tested
NFR-1 thread-safe one mutex, on_worker_thread step 1 scheduler.* ac_2_3_…, ac_6_6_…, group 8; tsan preset Tested
NFR-2 no lock in user code unlock in run_front; doomed in cancel step 1 scheduler.cpp ac_2_3_… (runs); ac_4_7_… (callable destroyed) Tested
NFR-3 no real time Clock, ManualClock, time_moved step 1 clock.hpp, scheduler.cpp ac_7_1_… to ac_7_3_…, ac_12_1_…, ac_12_2_… Tested
NFR-4 no allocation after acceptance new_slot, slot, extract/insert step 1 scheduler.* none: read from the code Stated
NFR-5 fixed pool threads_, the constructor step 1 scheduler.* ac_1_6_…, ac_8_1_… Tested
FR-8 retries RetryPolicy, backoff, finish_run step 2 task.hpp, scheduler.cpp ac_9_1_… to ac_9_9_… Tested
FR-9 dependencies TaskSpec, schedule_all, find_cycle, release_dependents, cancel_dependents step 2 scheduler.* ac_10_1_… to ac_10_19_…, ac_11_1_… to ac_11_5_… Tested

Exercise: A fixed gap instead of a fixed rate

A second team uses the scheduler to poll a slow service. They want 10 seconds of rest between polls, however long each poll takes, so they ask for a task that runs again a fixed gap after each run ends. Start from step 1.

  1. What should a poll that takes 3 seconds, with a gap of 10 seconds and a first delay of 10, give as start times?
  2. Where is the one place the next run is decided, and what does it need to know that it does not know today?
  3. Can a run with a fixed gap ever overlap itself, or miss a run? Why?
  4. Add schedule_with_gap(first_delay, gap, task), and a test for the start times and for a gap that is not positive.
Show the explained answer
  1. 10, 23, 36. The first run starts at 10 and ends at 13; the next starts 10 seconds after that, at 23, ends at 26; the next starts at 36. A fixed rate would give 10, 20, 30.

  2. The repeat branch of run_front. It computes next_slot(key.due, rec.period, clock_.now()). It needs to know, per task, which rule to use, so the record gets a flag, and add gets a parameter to set it:

    IllustrativeA fragment for explanation; not compiled on its own.

    // scheduler.hpp: in Record
    bool from_finish = false; // periodic: plan the next run from the end of this one
    // scheduler.hpp: the private add, with a default so the two callers need no change
    Scheduled add(Duration delay, Duration period, Task task, bool from_finish = false);
    // scheduler.cpp
    Scheduled Scheduler::schedule_with_gap(Duration first_delay, Duration gap, Task task) {
    if (gap <= Duration::zero()) return {0, Refusal::bad_period};
    return add(first_delay, gap, std::move(task), true);
    }
    // in add, next to rec.period = period;
    rec.from_finish = from_finish;
    // in run_front, the repeat branch
    const TimePoint now = clock_.now();
    const TimePoint next =
    rec.from_finish ? now + rec.period : next_slot(key.due, rec.period, now);
    make_due(rec, key.id, next);

    The flag is set before make_due, like every other field, so add still makes no change that can fail half-way, and run_front still allocates nothing.

  3. Neither. It cannot overlap for the same reason as a fixed-rate task: the next run is queued only after this one ends. It cannot miss a run, because the next run is always in the future when it is planned (the gap is positive), so there is nothing to skip.

  4. A test with a ManualClock, where the task moves the clock 3 seconds while it runs:

    IllustrativeA fragment for explanation; not compiled on its own.

    LLD_TEST(gap_counts_from_the_end_of_each_run) {
    ManualClock clock;
    Scheduler scheduler(clock, 1);
    std::string starts;
    const TaskId id = scheduler.schedule_with_gap(10s, 10s, [&] {
    starts += std::to_string(duration_cast<seconds>(clock.now().time_since_epoch()).count()) + " ";
    clock.advance(3s); // the run takes 3 seconds
    }).id;
    // 35 steps of one second, plus 3 seconds inside each run: the clock ends at 44,
    // before a fourth run (due at 49).
    for (int i = 0; i < 35; ++i) {
    clock.advance(1s);
    scheduler.wait_until_idle();
    }
    LLD_CHECK_EQ(starts, std::string("10 23 36 "));
    const TaskInfo info = scheduler.info(id).value();
    LLD_CHECK_EQ(info.runs, 3);
    }
    LLD_TEST(gap_refuses_a_gap_that_is_not_positive) {
    ManualClock clock;
    Scheduler scheduler(clock, 1);
    LLD_CHECK(scheduler.schedule_with_gap(1s, 0s, [] {}).refusal == Refusal::bad_period);
    }

    Calling clock.advance from inside a task is safe: the task runs with the scheduler’s lock released, and the waker takes it.

How this answer was checked: in the review (2026-11-28) the change above was made to a scratch copy of step 1 (not to the example), with these two tests added. Built with g++ 11.4 and clang++ 14 (-Wall -Wextra -Wconversion -Wshadow, no warnings), and once with g++ and ThreadSanitizer, all 42 tests (the 40 of step 1 and these two) passed each time. The two tests are shown here with a reformatted loop and a comment added. The example in the repository does not contain this change.

  • A scheduler is a thread pool fed by a time-ordered queue. A std::set ordered by due time and a sequence number gives the front, ties in queue order, and removal from the middle for cancel.
  • No task runs under the lock, and no callable is destroyed under it. The state running protects a task while the lock is released.
  • A periodic task keeps the beat of its planned times and skips the ones it missed. Planning from the finish is a different policy, to be chosen on purpose.
  • Cancel is honest: before the start it prevents the run; during it, it prevents the next one.
  • Shutdown refuses at once, drains what is already due or discards it, and joins every thread before it returns.
  • Inject the clock, and let it wake the workers. The waker must pass through the scheduler’s lock, or a moved clock can be missed.
  • Allocate when a task is accepted, so running, rescheduling, and cancelling cannot fail. Step 2 does the same for a whole batch, in four stages ending with steps that cannot throw.
  • Tests that make races likely are useful and limited; a test that forces one order is stronger and still limited. Mutating the code shows which mistakes a suite really catches.