Qué hace
- Cron de 5 o 6 campos, con <code>L</code>, <code>#</code> y nombres. Los errores indican el campo y el byte
- Zonas horarias a partir de reglas POSIX y TZif, horario de verano, saltos de reloj, máquina suspendida
- Política de solapamiento, jitter, plazo cooperativo y persistencia a través de una interfaz
Medido
- Tick en reposo con el tiempo proporcionado: 0.71 ns en GCC y 1.97 ns en MSVC (objetivo 20 ns)
- Siguiente disparo de una expresión cron: 154 a 502 ns (objetivo 1 µs)
- 400 expresiones aleatorias idénticas a una referencia independiente
Ethereal::Scheduler · Tier 2, small module
---
First, what already existed (the spec requires reading it before writing)
- Concurrency has
CJobManager, a thread pool, and nothing about time or calendars. - Time has the clocks (
IClock,NowMonotonic,NowRealtime), the timer wheel (in monotonic time, at millisecond resolution) and the civil calendar (Hinnant), but deliberately has no time zones with rules, only the current offset.
What was missing was the calendar, "every weekday at 03:00 local time", and that is what this module adds, as a thin layer: the clocks are the ones from Time, and the work runs on an IJobDispatcher that the integrator connects to CJobManager or to anything else. It is not a submodule of Concurrency, because it needs nothing from it: the dispatch seam is enough.
To pick the next job, an indexed binary heap is used (O(log n) to insert, remove and fix up), the alternative the spec allows. The Time wheel works in monotonic time at millisecond resolution, and a calendar job must be recomputed when the wall clock jumps.
---
Usage
#include <ethereal/cpp/pch/pch_ethereal.h> // or scheduler_inc.hpp
using namespace Ethereal;
Scheduler::CPosixTimeZone Zone;
Scheduler::CPosixTimeZone::FromSystem( &Zone ); // or Parse( "Europe..." in POSIX: "WET0WEST,M3.5.0/1,M10.5.0" )
Scheduler::SSchedulerParams P;
P.uMaxJobs = 32;
P.pZone = &Zone;
P.pDispatcher = &MyDispatcher; // null: runs inside Tick
Scheduler::CScheduler Sch;
Sch.Init( P ); // the only call that allocates memory
Scheduler::SJobSpec J;
J.sName = "backup";
J.pRun = &Backup; // ESchedulerError (*)( void *, const SJobContext & ) noexcept
J.bLocalTime = true;
Scheduler::SJobHandle H;
Sch.ScheduleCron( "0 3 * * MON-FRI", J, &H );
for( ;; )
{
Sch.Tick();
SleepFor( Sch.TimeUntilNext() ); // sleeps for exactly the right time, no fixed interval
}Cron: five fields, or six with the seconds in front. *, a-b, */n, a-b/n, a/n, lists, names (JAN, MON), 7 = Sunday, L in the day of the month, 5L (the last Friday), 1#2 (the second Monday), ?, and @yearly, @monthly, @weekly, @daily, @hourly, @reboot. An error reports the field and the byte. A field counts as * only if it is exactly * or ? (Vixie cron also treats */2 in the day of the week as *, which silently changes the day-of-month/day-of-week rule. That does not happen here). Ranges that wrap around (FRI-MON) are rejected.
Time zones: POSIX rules (EST5EDT,M3.2.0,M11.1.0), the current rules without the history, the same compromise as Time. FromSystem reads the footer of /etc/localtime (TZif v2+) or TZ on POSIX, and GetTimeZoneInformation on Windows. A time zone with daylight saving time but no rules is rejected: nothing is guessed.
---
The cases everyone gets wrong, one by one
| Case | What happens | Where it is proven |
|---|---|---|
| DST starts: 02:30 does not exist | EGapPolicy::eRunAfter (default) runs at the first valid instant after the jump. eSkip skips that day. Never silently | Schedule.SummerTheMissingHourRunsAfter, SummerWithSkipDoesNotRunThatDay |
| DST ends: 01:30 exists twice | runs once: on the first one (default) or on the second one (EFoldPolicy) | Schedule.WinterTheRepeatedHourRunsOnce |
| Clock jumps a year forward | the daily job runs once (with uMissed = 365), and the next run is tomorrow | Schedule.ClockJumpsAYearForwardWithoutAStorm |
| Clock goes backward | interval jobs (monotonic) notice nothing | Schedule.ClockJumpsBackIntervalsDoNotNotice |
| Laptop closed for a week | eRunOnce 1 time, eRunAll 7 times, eSkip 0 | Schedule.LaptopClosedForAWeek |
| Overlapping runs | eSkip (default) counts the skipped runs. eQueue with a limit. eConcurrent up to the slots set in Init | Schedule.OverlapSkipQueueConcurrent |
Ten thousand agents with @daily | default jitter on any period above one minute (10% of the period, up to 5 min), can be turned off with bNoJitter | Schedule.JitterUniformAndUncorrelated |
| Long job holding up the Tick | runs on the dispatcher. The deadline (Timeout) is cooperative: the Tick marks it as cancelled (IsCancelled()), reports it, counts the failure, and never waits | Schedule.TimeoutCancelsWithoutBlockingTheTick |
The wall clock is only seen when someone looks. With calendar jobs, the Tick checks it every WallCheckInterval (60 s by default), and that deadline is included in TimeUntilNext. It is a declared compromise: at most 1,440 wakeups per day, and a jump is caught within one minute. Without live calendar jobs there is no check at all: a rejected registration does not count, and a cancelled job or an At that has already fired stop counting. The first calendar job rereads the wall clock before planning itself, because it may have jumped while nobody was looking (Schedule.WallCheckOnlyWithLiveCalendar). This was a real defect, caught by the C layer test: a rejected cron turned the check on forever.
No distributed coordination. Leader election and single execution across a group of machines are out of scope, and this is recorded here because someone will ask.
---
Implementation status
| Criterion (spec §9) | Status |
|---|---|
| Idle Tick < 20 ns, one comparison | ✅ Tick(now): 0.71 ns (GCC) and 1.97 ns (MSVC). Tick() without an argument reads the clock first: 34.7 ns on GCC, of which 25.2 are NowMonotonic itself on this machine (WSL2). 20.1 ns on MSVC (the clock alone: 22.5 ns, that is, reading the clock is the whole cost). Code that has already read the clock uses Tick(now) |
| Background threads | ✅ zero (Schedule.NoOwnThreads counts them on Linux. On Windows the test is skipped with the reason, and the design creates none) |
| Zero allocations after registration | ✅ ETL_EXPECT_NO_ALLOC around registering, 60 Ticks with execution, pausing, resuming, triggering, status, cancelling |
| Next cron fire time < 1 µs, by bit scanning | ✅ 180 to 496 ns (GCC), 154 to 502 ns (MSVC). The worst cases are 5L and 1#2, which search day by day |
| Cron parsing: full syntax, errors with the exact location | ✅ 27 valid expressions. 13 invalid ones with the field and the byte verified |
| Differential against a reference, years of simulated time | ✅ independent reference (a different parser, using sets, searching minute by minute): 400 random expressions match. Five expressions followed for five years, fire by fire (up to 1,304 fires each) |
| DST start, DST end, jumps, laptop closed, overlap | ✅ see the table above |
| Uniform jitter, no correlation between instances | ✅ chi-square 13.6 (limit 21.7 at p = 0.01). Correlation between two instances −0.03 |
Persistence: the state survives, and eMisfire is applied at startup | ✅ with an in-memory IJobStore. The glue to Storage does not exist yet. The Storage module (spec 25) already exists, only the glue is missing |
| Deadline: cancels without holding up the Tick | ✅ cooperative, and that is what can be promised (there is no portable and safe way to kill a thread midway) |
| Sanitizers | ✅ ASan+UBSan and TSan (GCC 15.2): 23 of 23, zero reports, including the deadline with the job on a real thread |
| C ABI | ✅ ethereal/c/scheduler/scheduler.h, tested in C11 and C17. The manual clocks, the storage and the notifications do not cross over (they are C++ seams) |
Telemetry: the spec asks for the Telemetry glue to record counters and the duration histogram. The Telemetry module (spec 26) already exists, but that glue has not been written yet. Resilience: retries use the minimal built-in backoff (doubles on each attempt, up to 64×), not the Resilience seam.