Overview / System & concurrency

scheduler

Job calendar (for example, every weekday at 03:00 local time) with no thread of its own. It uses the <code>time</code> clocks and dispatches on an executor supplied by the integrator.

Always compiled: part of the core build.Include #include <ethereal/cpp/scheduler/scheduler_inc.hpp>C layer

scheduler_inc.hpp

#include <ethereal/cpp/scheduler/scheduler_inc.hpp>

Aggregate entry point of the Scheduler module.

The calendar that was missing ("every weekday at 03:00 local") on top of the Time clocks. No thread of its own (the integrator calls Tick), no allocations after Init, cron compiled to bit masks, time zones with POSIX rules for daylight saving time, and the cases everyone gets wrong handled one by one.

Including this header brings the whole module.

cron.hpp

#include <ethereal/cpp/scheduler/cron.hpp>

Cron expressions for the Scheduler module, compiled to bit masks.

An expression is parsed once, at registration. Each field becomes a mask (60 bits of seconds, 60 of minutes, 24 of hours, 31 of days, 12 of months, 7 of weekdays), and the next firing is found by scanning bits, never by trying candidate instants one by one.

Syntax: five fields (minute hour day-of-month month weekday), or six with the seconds in front. In each field: '', values, ranges 'a-b', steps '/n', 'a-b/n' and 'a/n' (from a to the end), lists 'a,b,c', names (JAN..DEC, SUN..SAT, case insensitive), and 7 is also Sunday. In the day of month, 'L' (the last day). In the weekday, 'dL' (the last d of the month: '5L' is the last Friday) and 'd#n' (the n-th: '1#1' is the first Monday). '?' means '*'. Shortcuts: @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly, @reboot.

Day of month and weekday follow the classic cron rule: when both are restricted, either one matching is enough (OR). When one is '', the other decides. A field only counts as '' when it is exactly '' or '?'. Vixie cron also treats '/2' in the weekday as '*', which silently changes the rule. This parser does not.

Ranges that wrap around are rejected with the error position. 'FRI-MON' is refused instead of guessing whether it means Friday to Monday or nothing.

struct

SCronExpr

Ethereal::Scheduler#
C++
struct   SCronExpr   final
{
    /// @brief  Bits 0..59. Only bit 0 when the expression has no seconds.
    ETL_UINT64    uSeconds = 1u;

    /// @brief  Bits 0..59.
    ETL_UINT64    uMinutes = 0u;

    /// @brief  Bits 0..23.
    ETL_UINT32    uHours = 0u;

    /// @brief  Bits 1..31.
    ETL_UINT32    uDaysOfMonth = 0u;

    /// @brief  Bits 1..12.
    ETL_UINT16    uMonths = 0u;

    /// @brief  Bits 0..6, 0 = Sunday.
    ETL_UINT8    uWeekdays = 0u;

    /// @brief  Per weekday: bit n (1..5) = the n-th, bit 6 = the last.
    ETL_UINT8    aNthWeekday[ 7 ] = {};

    /// @brief  The day of month field is exactly '*' or '?'.
    bool        bDomStar = false;

    /// @brief  The weekday field is exactly '*' or '?'.
    bool        bDowStar = false;

    /// @brief  'L' in the day of month.
    bool        bLastDom = false;

    /// @brief  '@reboot': fires once, at startup.
    bool        bReboot = false;

    /// @brief  The expression has the seconds field.
    bool        bHasSeconds = false;
};

A compiled cron expression. POD.

struct

SCronError

Ethereal::Scheduler#
C++
struct   SCronError   final
{
    /// @brief  The field (0 = the first one written). ~0 when the error is about the whole.
    ETL_UINT32        uField = ~0u;

    /// @brief  The character, from the start of the expression.
    std::size_t        uOffset = 0u;

    /// @brief  The message. Static, never freed.
    const char *    sMessage = "";
};

Where and why the parser failed.

function

ParseCron

Ethereal::Scheduler#
bool ParseCron( std::string_view sExpr, SCronExpr * pOut, SCronError * pError = nullptr ) noexcept;

Parses an expression.

sExpr
The expression text.
pOut
Receives the compiled expression.
pError
Receives the field, the position and the message on failure. May be null.
true on success.
Does not allocate. Thread safety: full.
function

CronMatches

Ethereal::Scheduler#
bool CronMatches( const SCronExpr & Expr, const Time::SCivilTime & When ) noexcept;

Tells whether a civil date matches the expression.

Down to the second when the expression has seconds. Otherwise the second must be 0.

Expr
The compiled expression.
When
The civil date.
true when it matches.
function

NextCronFire

Ethereal::Scheduler#
bool NextCronFire( const SCronExpr & Expr, const Time::SCivilTime & After, Time::SCivilTime * pOut ) noexcept;

The first civil instant strictly after After that matches.

Scans bits field by field. Searches up to 400 years (one whole Gregorian cycle): an expression that does not fire in that time (February 30) never fires, and the function returns false.

Expr
The compiled expression.
After
The search starts right after this instant.
pOut
Receives the instant found.
true when an instant was found.
Does not allocate. Thread safety: full.

scheduler.hpp

#include <ethereal/cpp/scheduler/scheduler.hpp>

The job scheduler: a thin layer over the Time clocks.

Concurrency already has CJobManager (a thread pool) and no notion of time. Time has the clocks and the timer wheel, in monotonic time. What was missing is the calendar ("every weekday at 03:00 local"), and that is what this module adds. The rest is composition: the clocks are the Time ones (IClock), and the work runs on an IJobDispatcher that the integrator connects to CJobManager or to anything else.

No thread of its own. The integrator calls Tick (or Tick(now)) and uses TimeUntilNext to sleep the right amount. A library that starts a thread just by being linked is not acceptable.

A Tick with nothing to do is one comparison: the next deadline is cached (and includes the next wall clock check). Tick() without an argument reads the clock first, and that read costs what the clock costs (measured in the README).

No allocations after Init: the job table, the queues and the running executions are reserved there. Scheduling, cancelling, pausing and running do not allocate.

The cases, one by one (the spec calls them the real content of the module):

  • Daylight saving, the hour that does not exist: EGapPolicy. Runs at the first valid instant after the jump (default), or skips that day. Never silently.
  • Back to standard time, the hour that exists twice: runs once, on the first (default) or on the second. Never twice.
  • The wall clock jumps (NTP, manual change, a resumed virtual machine): interval jobs use the monotonic clock and are not affected. Calendar jobs recompute the next firing against the new time, and a jump of one year forward does not set off a storm of late firings.
  • Sleeping machine or stopped process: EMisfirePolicy. eRunOnce (default): a laptop closed for a week runs the daily job once when it wakes up.
  • Overlapping executions: eSkip (default), since the alternative piles up delays without bound. eQueue has a limit (uQueueLimit). eConcurrent has the limit of running executions reserved in Init.
  • Jitter: ten thousand agents with '@daily' firing at 00:00 are an attack on the customer's server. Any interval above one minute gets jitter by default (10% of the interval, up to 5 minutes), and it must be turned off explicitly.

The Timeout is cooperative: there is no portable and safe way to kill a thread halfway. When the deadline passes, Tick marks the execution as cancelled (the job reads SJobContext::IsCancelled()), calls the timeout callback and counts the failure. Tick never waits for it.

No distributed coordination: leader election and single execution across a group of machines are out of scope, and are stated here because someone will ask.

enum

ESchedulerError

Ethereal::Scheduler#
C++
enum class   ESchedulerError : ETL_INT32
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  A parameter is out of range.
    eInvalidArgument,

    /// @brief  Init was not called.
    eNotInitialized,

    /// @brief  Init was already called.
    eAlreadyInitialized,

    /// @brief  The job table (or the execution table) is full.
    eFull,

    /// @brief  Stale or unknown handle.
    eNotFound,

    /// @brief  The expression does not parse (the position comes in SCronError).
    eBadCron,

    /// @brief  The expression parses but never fires (February 30).
    eNeverFires,

    /// @brief  The queue of the job is full.
    eQueueFull,

    /// @brief  Returned by a job to tell that it failed.
    eJobFailed,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///          ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

Result codes of the scheduler.

enum

EOverlapPolicy

Ethereal::Scheduler#
C++
enum class   EOverlapPolicy : ETL_UINT8        { eSkip = 0, eQueue, eConcurrent };

What to do when a firing arrives while the job is still running.

enum

EMisfirePolicy

Ethereal::Scheduler#
C++
enum class   EMisfirePolicy : ETL_UINT8        { eRunOnce = 0, eRunAll, eSkip };

What to do with firings missed while the process was stopped or late.

enum

EGapPolicy

Ethereal::Scheduler#
C++
enum class   EGapPolicy : ETL_UINT8            { eRunAfter = 0, eSkip };

What to do with a local time that does not exist (daylight saving gap).

enum

EFoldPolicy

Ethereal::Scheduler#
C++
enum class   EFoldPolicy : ETL_UINT8        { eFirst = 0, eSecond };

Which occurrence of a local time that exists twice runs.

enum

EJobState

Ethereal::Scheduler#
C++
enum class   EJobState : ETL_UINT8            { eIdle = 0, eRunning, ePaused, eDone };

State of a job.

struct

SJobHandle

Ethereal::Scheduler#
C++
struct   SJobHandle   final
{
    /// @brief  Slot of the job in the table.
    ETL_UINT32    uIndex = 0xFFFFFFFFu;

    /// @brief  Generation of the slot when the job was scheduled.
    ETL_UINT32    uGeneration = 0u;

    /// @brief  true when the handle points to a slot.
    ///
    ETL_API_NOIGN    bool IsValid() const ETL_NOEXCEPT    { return uIndex != 0xFFFFFFFFu; }
};

A job handle: index and generation (a stale handle never touches a successor).

struct

SJobContext

Ethereal::Scheduler#
C++
struct   SJobContext   final
{
    /// @brief  Handle of the job.
    SJobHandle                    Handle;

    /// @brief  Name of the job.
    std::string_view            sName;

    /// @brief  The firing this execution stands for (UTC seconds, 0 = manual).
    ETL_INT64                    iScheduledUtc = 0;

    /// @brief  0 on the first attempt, 1.. on the retries.
    ETL_UINT32                    uAttempt = 0u;

    /// @brief  Missed firings covered by this execution (eRunOnce).
    ETL_UINT32                    uMissed = 0u;

    /// @brief  Started by TriggerNow.
    bool                        bManual = false;

    /// @brief  Cancel flag, set by Cancel or by the timeout.
    const std::atomic< bool > *    pCancel = nullptr;

    /// @brief  The deadline passed, or the job was cancelled: leave when you can.
    ///
    ETL_API_NOIGN    bool IsCancelled() const ETL_NOEXCEPT    { return pCancel != nullptr && pCancel->load( std::memory_order_acquire ); }
};

What a job sees when it runs.

alias

ESchedulerError

Ethereal::Scheduler#
using FJobRun = ESchedulerError ( * )( void * pContext, const SJobContext & Ctx ) noexcept;

The function a job runs.

struct

SJobSpec

Ethereal::Scheduler#
C++
struct   SJobSpec   final
{
    /// @brief  sizeof( SJobSpec ), checked by the scheduler.
    ETL_UINT32            uStructSize = static_cast< ETL_UINT32 >( sizeof( SJobSpec ) );

    /// @brief  The name. Copied into the table (up to 63 bytes). Persistence uses it as the key.
    std::string_view    sName;

    /// @brief  Context passed to pRun.
    void *                pContext = nullptr;

    /// @brief  The function the job runs.
    FJobRun                pRun = nullptr;

    /// @brief  Overlap policy.
    EOverlapPolicy        eOverlap = EOverlapPolicy::eSkip;

    /// @brief  Misfire policy.
    EMisfirePolicy        eMisfire = EMisfirePolicy::eRunOnce;

    /// @brief  Daylight saving gap policy.
    EGapPolicy            eGap = EGapPolicy::eRunAfter;

    /// @brief  Repeated local time policy.
    EFoldPolicy            eFold = EFoldPolicy::eFirst;

    /// @brief  Deadline of one execution. Zero: no deadline.
    Time::SDuration        Timeout{};

    /// @brief  Retries after a failure.
    ETL_UINT32            uMaxRetries = 0u;

    /// @brief  Delay before a retry. Doubles on each attempt, up to 64x.
    Time::SDuration        RetryBackoff = Time::Seconds( 1 );

    /// @brief  The jitter window. Zero: the default (10% of the interval above one minute, up to 5 min).
    Time::SDuration        Jitter{};

    /// @brief  Turns the jitter off, including the default one.
    bool                bNoJitter = false;

    /// @brief  Cron in local time (the zone of SSchedulerParams). UTC by default.
    bool                bLocalTime = false;

    /// @brief  Stores the last successful firing in the IJobStore, and applies eMisfire at startup.
    bool                bPersistent = false;

    /// @brief  eQueue: how many executions may wait. Never unbounded.
    ETL_UINT32            uQueueLimit = 4u;
};

Description of a job, given when it is scheduled.

struct

SJobStatus

Ethereal::Scheduler#
C++
struct   SJobStatus   final
{
    /// @brief  Handle of the job.
    SJobHandle            Handle;

    /// @brief  Name of the job. Valid while the job exists.
    std::string_view    sName;

    /// @brief  State of the job.
    EJobState            eState = EJobState::eIdle;

    /// @brief  Last execution, UTC seconds. 0 = never.
    ETL_INT64            iLastRunUtc = 0;

    /// @brief  Result of the last execution.
    ESchedulerError        eLastResult = ESchedulerError::eOk;

    /// @brief  Duration of the last execution.
    Time::SDuration        LastDuration{};

    /// @brief  Next firing, UTC seconds. 0 = none (paused, done).
    ETL_INT64            iNextFireUtc = 0;

    /// @brief  Failures in a row.
    ETL_UINT32            uConsecutiveFailures = 0u;

    /// @brief  Executions so far.
    ETL_UINT64            uTotalRuns = 0u;

    /// @brief  Firings missed so far.
    ETL_UINT64            uMissedFires = 0u;

    /// @brief  Firings skipped because of an overlap.
    ETL_UINT64            uSkippedOverlaps = 0u;

    /// @brief  Executions running now.
    ETL_UINT32            uRunning = 0u;

    /// @brief  Executions waiting in the queue.
    ETL_UINT32            uQueued = 0u;
};

State of a job, as returned by JobStatus.

struct

IJobDispatcher

Ethereal::Scheduler#
C++
struct   IJobDispatcher
{
    ///
    /// Dispatch
    ///
    /// @brief  Runs pFn( pArg ) somewhere.
    ///
    /// @param pFn        The function to run.
    /// @param pArg        Its argument.
    ///
    /// @return  false when it was not accepted (queue full). The scheduler counts it as
    ///              a skipped overlap.
    ///
    virtual bool Dispatch( void ( *pFn )( void * ), void * pArg ) ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor.
    ///
    virtual ~IJobDispatcher() = default;
};

Where the work runs. Without a dispatcher it runs inside Tick (an explicit choice).

struct

SPersistedJob

Ethereal::Scheduler#
C++
struct   SPersistedJob   final
{
    /// @brief  Last successful firing, UTC seconds.
    ETL_INT64    iLastSuccessUtc = 0;
};

What is persisted for a job.

struct

IJobStore

Ethereal::Scheduler#
C++
struct   IJobStore
{
    /// @brief  Loads the state of a job. false when there is none.
    ///
    virtual bool Load( std::string_view sName, SPersistedJob * pOut ) ETL_NOEXCEPT = 0;

    /// @brief  Saves the state of a job.
    ///
    virtual bool Save( std::string_view sName, const SPersistedJob & State ) ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor.
    ///
    virtual ~IJobStore() = default;
};

The persistence seam (Storage connects here through glue).

struct

SSchedulerCallbacks

Ethereal::Scheduler#
C++
struct   SSchedulerCallbacks   final
{
    /// @brief  Context passed to every callback.
    void *    pContext = nullptr;

    /// @brief  An execution started.
    void    ( *pOnStart )( void * pCtx, const SJobContext & ) ETL_NOEXCEPT = nullptr;

    /// @brief  An execution succeeded, with its duration.
    void    ( *pOnSuccess )( void * pCtx, const SJobContext &, Time::SDuration ) ETL_NOEXCEPT = nullptr;

    /// @brief  An execution failed, with the error.
    void    ( *pOnFailure )( void * pCtx, const SJobContext &, ESchedulerError ) ETL_NOEXCEPT = nullptr;

    /// @brief  An execution passed its deadline.
    void    ( *pOnTimeout )( void * pCtx, const SJobContext & ) ETL_NOEXCEPT = nullptr;
};

The callbacks, called outside any lock.

struct

SSchedulerParams

Ethereal::Scheduler#
C++
struct   SSchedulerParams   final
{
    /// @brief  sizeof( SSchedulerParams ), checked by Init.
    ETL_UINT32                uStructSize = static_cast< ETL_UINT32 >( sizeof( SSchedulerParams ) );

    /// @brief  Capacity of the job table.
    std::size_t                uMaxJobs = 64u;

    /// @brief  Executions running at the same time, in total.
    std::size_t                uMaxRunning = 64u;

    /// @brief  Monotonic clock. Null: the system one.
    Time::IClock *            pMonotonic = nullptr;

    /// @brief  Wall clock. Null: NowRealtime.
    Time::IClock *            pWall = nullptr;

    /// @brief  Time zone. Null: UTC (only used with bLocalTime).
    const ITimeZone *        pZone = nullptr;

    /// @brief  Dispatcher. Null: runs inside Tick.
    IJobDispatcher *        pDispatcher = nullptr;

    /// @brief  Persistence. Null: nothing is persisted.
    IJobStore *                pStore = nullptr;

    /// @brief  How often Tick checks the wall clock (only with calendar jobs). A stated
    ///             trade-off: a clock jump (the laptop that wakes up) is only seen by looking,
    ///             and each look is a wake-up. With 60 s that is at most 1440 wake-ups a day,
    ///             and a jump is seen within one minute.
    Time::SDuration            WallCheckInterval = Time::Seconds( 60 );

    /// @brief  A gap larger than this between the wall and the monotonic clock recomputes
    ///             the calendar jobs.
    Time::SDuration            WallJumpTolerance = Time::Seconds( 2 );

    /// @brief  Delay after which a firing counts as missed.
    Time::SDuration            MisfireThreshold = Time::Seconds( 60 );

    /// @brief  eRunAll: maximum number of missed firings that are run.
    ETL_UINT32                uMaxCatchUp = 100u;

    /// @brief  Zero: a seed from the clock and the address (two instances do not correlate).
    ETL_UINT64                uJitterSeed = 0u;

    /// @brief  The callbacks.
    SSchedulerCallbacks        Callbacks;
};

Scheduler parameters.

class

CScheduler

Ethereal::Scheduler#

The scheduler.

class CScheduler final
constructor

CScheduler

#
CScheduler() noexcept;

Default constructor. Call Init before use.

function

Init

#
ESchedulerError Init( const SSchedulerParams & Params ) noexcept;

Reserves everything the scheduler will need. The only call that allocates.

Params
Scheduler parameters.
eOk, eAlreadyInitialized or eInvalidArgument. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

ScheduleEvery

#
ESchedulerError ScheduleEvery( Time::SDuration Interval, const SJobSpec & Spec, SJobHandle * pOut ) noexcept;

Schedules a job that runs at a fixed interval, on the monotonic clock.

Interval
The interval. Must be positive.
Spec
The job.
pOut
Receives the handle.
eOk, eFull, eNotInitialized or eInvalidArgument.
function

ScheduleAfter

#
ESchedulerError ScheduleAfter( Time::SDuration Delay, const SJobSpec & Spec, SJobHandle * pOut ) noexcept;

Schedules a job that runs once, after a delay on the monotonic clock.

Delay
The delay. Must not be negative.
Spec
The job.
pOut
Receives the handle.
eOk, eFull, eNotInitialized or eInvalidArgument.
function

ScheduleAt

#
ESchedulerError ScheduleAt( Time::STimePoint When, const SJobSpec & Spec, SJobHandle * pOut ) noexcept;

Schedules a job that runs once, at an instant of the wall clock (UTC).

When
The instant.
Spec
The job.
pOut
Receives the handle.
eOk, eFull, eNotInitialized or eInvalidArgument.
function

ScheduleCron

#
ESchedulerError ScheduleCron( std::string_view sExpr, const SJobSpec & Spec, SJobHandle * pOut, SCronError * pError = nullptr ) noexcept;

Schedules a job by a cron expression.

sExpr
The expression.
Spec
The job.
pOut
Receives the handle.
pError
Receives the parser error. May be null.
eOk, eBadCron, eNeverFires, eFull, eNotInitialized or eInvalidArgument.
function

Pause

#
ESchedulerError Pause( SJobHandle H ) noexcept;

Pauses a job. Running executions are not stopped.

function

Resume

#
ESchedulerError Resume( SJobHandle H ) noexcept;

Resumes a paused job, counting from now.

function

Cancel

#
ESchedulerError Cancel( SJobHandle H ) noexcept;

Cancels a job. With executions running, they are asked to leave and the slot is freed on the last one.

function

TriggerNow

#
ESchedulerError TriggerNow( SJobHandle H ) noexcept;

A manual execution, outside the calendar. Follows the overlap policy.

function

Tick

#
ESchedulerError Tick() noexcept;

Runs whatever is due. Reads the monotonic clock.

function

Tick

#
ESchedulerError Tick( const Time::STimePoint Now ) noexcept

The same, with the monotonic instant already read. With nothing to do, one comparison.

function

TimeUntilNext

#
Time::SDuration TimeUntilNext() const noexcept;

How long to sleep until there is work. Negative: nothing scheduled.

function

JobStatus

#
ESchedulerError JobStatus( SJobHandle H, SJobStatus * pOut ) const noexcept;

State of a job.

function

EnumJobs

#
ESchedulerError EnumJobs( bool ( *pFn )( void * pCtx, const SJobStatus & ), void * pCtx ) const noexcept;

Walks the jobs. The callback returns false to stop.

function

EnumJobs

#
template < class F > ESchedulerError EnumJobs( F && Fn ) const noexcept

The same, with any callable.

function

RunningCount

#
std::size_t RunningCount() const noexcept;

Executions running now (for whoever wants to wait before destroying).

timezone.hpp

#include <ethereal/cpp/scheduler/timezone.hpp>

Time zones for the Scheduler module (POSIX rules).

The Time module only gives the offset of now (LocalOffset) and does not ship the IANA database on purpose. A scheduler needs more: it must know that "02:30 on Sunday" does not exist on the night the clock jumps forward, and that "01:30" exists twice on the night it goes back.

The answer here is the POSIX 'TZ' rules. "EST5EDT,M3.2.0,M11.1.0" gives the standard offset, the daylight offset and the two change rules. They are the current rules, not the history (the same trade-off as the Time module), and they are what the system itself uses for the future: the footer of a TZif file (/etc/localtime) is one of these strings, and Windows stores the zone as exactly these two rules.

Everything is in UTC seconds since 1970. The scheduler works at second resolution.

The types of this module do not use ETL_STRUCT_ALIGN. It aligns to 32 bytes, and on a 12 byte rule that only adds padding (MSVC warns with C4324) and speeds up nothing.

enum

ELocalKind

Ethereal::Scheduler#
C++
enum class   ELocalKind : ETL_UINT8
{
    /// @brief  The local time exists once.
    eUnique = 0,

    /// @brief  The local time does not exist: the clock jumped forward over it.
    eGap,

    /// @brief  The local time exists twice: the clock went back.
    eAmbiguous
};

What happens to a local time on a given day.

struct

SLocalResolution

Ethereal::Scheduler#
C++
struct   SLocalResolution   final
{
    /// @brief  Kind of the local time.
    ELocalKind    eKind = ELocalKind::eUnique;

    /// @brief  eUnique: the instant. eAmbiguous: the first (earlier) occurrence.
    ///             eGap: the first valid instant after the jump (the moment of the change).
    ETL_INT64    iUtcFirst = 0;

    /// @brief  eAmbiguous: the second occurrence. Otherwise equal to iUtcFirst.
    ETL_INT64    iUtcSecond = 0;
};

A local time converted to UTC.

struct

ITimeZone

Ethereal::Scheduler#
C++
struct   ITimeZone
{
    /// @brief  Seconds to add to UTC to get the local time, at that instant.
    ///
    virtual ETL_INT32 OffsetAt( ETL_INT64 iUtcSeconds ) const ETL_NOEXCEPT = 0;

    /// @brief  A local civil date in UTC, with the gap and the ambiguity reported.
    ///
    virtual SLocalResolution Resolve( const Time::SCivilTime & Local ) const ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor.
    ///
    virtual ~ITimeZone() = default;
};

The time zone seam.

Thread safety: the implementations in this file are immutable once built.
class

CFixedOffsetZone

Ethereal::Scheduler#

A fixed offset, without daylight saving time. UTC is this with zero.

class CFixedOffsetZone final : public ITimeZone
constructor

CFixedOffsetZone

#
explicit CFixedOffsetZone( const ETL_INT32 iOffsetSeconds = 0 ) noexcept : m_iOffset( iOffsetSeconds )

Builds the zone with the given offset, in seconds east of UTC.

function

OffsetAt

#
ETL_INT32 OffsetAt( ETL_INT64 ) const noexcept override

The fixed offset, at any instant.

function

Resolve

#
SLocalResolution Resolve( const Time::SCivilTime & Local ) const noexcept override;

A local civil date in UTC. Always eUnique.

function

UtcZone

Ethereal::Scheduler#
const ITimeZone * UtcZone() noexcept;

The shared UTC zone. Immutable.

struct

STzRule

Ethereal::Scheduler#
C++
struct   STzRule   final
{
    /// @brief  How the day of the change is written.
    ///
    enum class   EForm : ETL_UINT8
    {
        /// @brief  Jn: day 1..365, February 29 never counts.
        eJulianNoLeap,

        /// @brief  n: day 0..365, February 29 counts.
        eJulian,

        /// @brief  Mm.w.d: day d (0 = Sunday) of week w (5 = the last) of month m.
        eMonthWeekDay
    };

    /// @brief  Form of the rule.
    EForm        eForm = EForm::eMonthWeekDay;

    /// @brief  Day of the Jn and n forms.
    ETL_UINT16    uDay = 0u;

    /// @brief  Month of the Mm.w.d form.
    ETL_UINT8    uMonth = 0u;

    /// @brief  Week of the Mm.w.d form.
    ETL_UINT8    uWeek = 0u;

    /// @brief  Weekday of the Mm.w.d form.
    ETL_UINT8    uWeekday = 0u;

    /// @brief  Local time of the change, in seconds (02:00 by default). May be
    ///             negative or go past 24h.
    ETL_INT32    iTime = 7200;
};

A time change rule, in the POSIX form.

class

CPosixTimeZone

Ethereal::Scheduler#

A time zone with the POSIX rules: the standard offset and, optionally, the daylight offset and the two changes.

class CPosixTimeZone final : public ITimeZone
constructor

CPosixTimeZone

#
CPosixTimeZone() = default;

Default constructor. The zone is UTC.

function

Parse

#
static bool Parse( std::string_view sTz, CPosixTimeZone * pOut, std::size_t * pErrorOffset = nullptr ) noexcept;

Reads a POSIX string ("UTC0", "CET-1CEST,M3.5.0,M10.5.0/3", "<-03>3", "AEST-10AEDT,M10.1.0,M4.1.0/3").

sTz
The POSIX string.
pOut
Receives the zone.
pErrorOffset
Receives where the parser stopped, on failure.
false for a string that is not valid POSIX. Nothing is guessed.
function

FromSystem

#
static bool FromSystem( CPosixTimeZone * pOut ) noexcept;

The system zone, by the rules the system uses for the future: the footer of /etc/localtime (TZif v2+) or 'TZ' on POSIX, and GetDynamicTimeZoneInformation on Windows.

pOut
Receives the zone.
false when the system does not expose the rules (pOut is left as UTC).
function

OffsetAt

#
ETL_INT32 OffsetAt( ETL_INT64 iUtcSeconds ) const noexcept override;

Seconds to add to UTC to get the local time, at that instant.

function

Resolve

#
SLocalResolution Resolve( const Time::SCivilTime & Local ) const noexcept override;

A local civil date in UTC, with the gap and the ambiguity reported.

function

HasDst

#
bool HasDst() const noexcept

true when the zone has daylight saving time.

function

StdOffset

#
ETL_INT32 StdOffset() const noexcept

Standard offset, in seconds east of UTC.

function

DstOffset

#
ETL_INT32 DstOffset() const noexcept

Daylight offset, in seconds east of UTC.

function

TransitionUtc

#
ETL_INT64 TransitionUtc( ETL_INT32 iYear, bool bStart ) const noexcept;

The UTC instant of a change in the given year.

iYear
The year.
bStart
true for the change to daylight time, false for the change back.
The instant, in UTC seconds since 1970.
function

CivilToSeconds

Ethereal::Scheduler#
ETL_INT64 CivilToSeconds( const Time::SCivilTime & Civil ) noexcept;

Seconds since 1970 of a civil date read as UTC (no zone).

function

SecondsToCivil

Ethereal::Scheduler#
Time::SCivilTime SecondsToCivil( ETL_INT64 iSeconds ) noexcept;

The inverse: the civil date of a count of seconds since 1970.