timers

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package timers contains calendar expression parsing and monotonic scheduling.

The scheduler is internal to winunitd (DESIGN.md §17–§18). It does not proxy Task Scheduler. OnBootSec is relative to machine boot; OnStartupSec is relative to this winunitd instance (monotonic SinceStart). Clock.Timer / Fake.Advance drive waits without sleeping on the real clock (issue #28). Engine.ClockChanged recomputes OnCalendar / OnUnitActiveSec deadlines after a wall jump and wakes the loop; OnBootSec heap entries are not rewritten. Status reports the scheduled next (a.next), refreshed on Arm, fire, UnitActive, and ClockChanged — not a per-call calendar search. A 30s poll remains as fallback when the host does not deliver TIMECHANGE.

Index

Constants

View Source
const MaxArmedTimers = 1024
View Source
const MaxCalendarExpressions = 64

Variables

This section is empty.

Functions

func MarkFired

func MarkFired(spec Spec, rt *Runtime, clk Clock, scheduled, actual time.Time)

MarkFired records that a deadline was consumed so one-shot relative triggers (OnBootSec / OnStartupSec) do not repeat for this activation.

func NextDeadline

func NextDeadline(spec Spec, rt Runtime, clk Clock) (time.Time, bool)

NextDeadline is the earliest due time for spec given rt and clk. ok is false when nothing is scheduled (for example only OnUnitActiveSec and the activated unit has never been active).

Types

type Activation

type Activation struct {
	ID        string    `json:"id"`
	Unit      string    `json:"unit"`
	Result    string    `json:"result"`
	Scheduled time.Time `json:"scheduled"`
	Actual    time.Time `json:"actual"`
}

Activation is a persistent calendar delivery attempt. A recovered pending record retains its ID; success/failure describes activation, not workload exit.

type Calendar

type Calendar struct {
	Raw string

	// RestrictWeekdays is true when the expression names weekdays
	// (for example Mon..Fri). When false, every weekday matches.
	RestrictWeekdays bool
	Weekdays         [7]bool // indexed by time.Weekday

	// Year, Month, Day use -1 as wildcard (*).
	Year  int
	Month int
	Day   int

	Hour   int
	Minute int
	Second int
	// contains filtered or unexported fields
}

Calendar is a parsed OnCalendar= expression.

MVP forms: "daily", "Mon..Fri 03:00", and "*-*-* HH:MM:SS" (seconds optional). Weekday names may be abbreviated or full.

func ParseCalendar

func ParseCalendar(s string) (Calendar, error)

ParseCalendar parses an OnCalendar= value.

func (Calendar) AllowsWeekday

func (c Calendar) AllowsWeekday(d time.Weekday) bool

AllowsWeekday reports whether d is included in the expression.

func (Calendar) Next

func (c Calendar) Next(after time.Time) time.Time

Next returns the next matching instant strictly after after. Zero means no future match in a reasonable search window.

func (Calendar) Previous

func (c Calendar) Previous(before time.Time) time.Time

Previous returns the latest matching instant strictly before before. Zero means no past match in a reasonable search window.

type Clock

type Clock struct {
	Now        func() time.Time
	SinceBoot  func() time.Duration
	SinceStart func() time.Duration
	Startup    time.Time
	NewTimer   func(d time.Duration) Timer
	Changed    <-chan struct{}
}

Clock is the scheduler's view of wall time, machine boot, and this winunitd instance start (DESIGN.md §17–§18).

OnBootSec is measured from machine boot. OnStartupSec is measured from this instance (Clock.SinceStart). They differ after an SCM restart of winunitd.

NewTimer, if set, is used instead of time.NewTimer so a fake can Advance time. Changed, if set, is signaled on a discontinuous wall jump (manual clock, DST, resume) so the engine recalculates calendar deadlines instead of sleeping until a stale monotonic wait. The host also calls Engine.ClockChanged on SERVICE_CONTROL_TIMECHANGE / POWEREVENT (PBT_APMRESUMEAUTOMATIC). A 30s poll remains as fallback.

SinceStart, if set, is monotonic time since this winunitd instance started (OnStartupSec). Nil means now.Sub(Startup) (wall).

func DefaultClock

func DefaultClock() Clock

DefaultClock uses the wall clock, platform boot time, and "now" as the instance start.

func (Clock) Timer

func (c Clock) Timer(d time.Duration) Timer

Timer returns a one-shot wait of d. Tests drive a fake with Advance.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is an internal timer scheduler (not Task Scheduler).

func NewEngine

func NewEngine(clk Clock, store *Store, fire FireFunc) *Engine

NewEngine starts a scheduler goroutine. Stop it with Stop.

func (*Engine) Arm

func (e *Engine) Arm(spec Spec) uint64

Arm starts or refreshes a timer. Existing FiredBoot/FiredStartup and last unit-active time are kept so refresh does not re-fire one-shot relatives. Each arm receives a new callback identity, returned to the caller.

func (*Engine) Armed

func (e *Engine) Armed(name string) bool

Armed reports whether name is currently scheduled.

func (*Engine) Clock

func (e *Engine) Clock() Clock

Clock returns the engine clock.

func (*Engine) ClockChanged

func (e *Engine) ClockChanged()

ClockChanged recomputes wall-clock (OnCalendar / OnUnitActiveSec) deadlines and wakes the loop so missed calendar events fire promptly (DESIGN.md §18). Monotonic OnBootSec / OnStartupSec heap entries are not rewritten. The 30s poll remains as a fallback.

func (*Engine) Current

func (e *Engine) Current(name string, token uint64) bool

Current reports whether an event still belongs to the current arm.

func (*Engine) Disarm

func (e *Engine) Disarm(name string)

Disarm stops a timer. Persistent last-run times stay on disk.

func (*Engine) RecordResult

func (e *Engine) RecordResult(event Fire, success bool)

RecordResult stores last successful execution after the activated unit start attempt.

func (*Engine) Retain

func (e *Engine) Retain(keep map[string]bool)

Retain disarms every timer not in keep.

func (*Engine) Retry

func (e *Engine) Retry(event Fire)

Retry retains an activation rejected before manager admission. Persistent calendar retries keep their durable intent identity; other retries retain their in-memory arm identity. Neither records a successful execution.

func (*Engine) Status

func (e *Engine) Status(name string) Snapshot

Status copies accepted next/last state without performing calendar searches. Next is absent while storage or calendar planning is pending, and otherwise matches the indexed heap deadline.

func (*Engine) Stop

func (e *Engine) Stop()

Stop ends the scheduler goroutine and waits for in-flight fire callbacks. It is idempotent.

func (*Engine) UnitActive

func (e *Engine) UnitActive(unit string, when time.Time)

UnitActive records that the activated unit last became active, for OnUnitActiveSec.

type Fake

type Fake struct {
	// contains filtered or unexported fields
}

Fake is a test clock. Advance moves wall time and SinceBoot together and fires due NewTimer waits. JumpWall changes only wall time. Suspend models Windows resume: uptime includes sleep, so both clocks and due waits advance. Both discontinuities signal Clock.Changed for wall deadline reconciliation.

func NewFake

func NewFake(now time.Time) *Fake

NewFake starts at now. A zero now uses 2026-09-01 12:00 UTC.

func (*Fake) Advance

func (f *Fake) Advance(d time.Duration)

Advance moves wall time and SinceBoot forward by d and fires every NewTimer whose deadline is at or before the new now.

func (*Fake) Clock

func (f *Fake) Clock() Clock

Clock is a Clock bound to this Fake. Startup is the Fake's start instant and does not move with Advance.

func (*Fake) JumpWall

func (f *Fake) JumpWall(to time.Time)

JumpWall sets wall time without moving SinceBoot and signals Changed. Pending NewTimer waits are not fired (those are monotonic).

func (*Fake) NextWhen

func (f *Fake) NextWhen() (time.Time, bool)

NextWhen is the earliest pending NewTimer deadline, if any.

func (*Fake) Now

func (f *Fake) Now() time.Time

Now is the current wall time.

func (*Fake) SinceBoot

func (f *Fake) SinceBoot() time.Duration

SinceBoot is the monotonic duration since machine boot.

func (*Fake) SinceStart

func (f *Fake) SinceStart() time.Duration

SinceStart is monotonic time since this Fake was created. Advance and Suspend move it; JumpWall does not.

func (*Fake) Suspend

func (f *Fake) Suspend(d time.Duration)

Suspend advances wall time and uptime together, as Windows does across sleep and hibernation. Due waits become observable on resume, followed by Changed.

func (*Fake) Waiting

func (f *Fake) Waiting() bool

Waiting reports whether any NewTimer is pending. Tests wait for the engine or manager to arm a fake wait before Advance.

func (*Fake) WaitingAt

func (f *Fake) WaitingAt(d time.Duration) bool

WaitingAt reports whether a pending NewTimer deadline is exactly now+d. NextWhen is the earliest deadline, so a shorter wait hides WatchdogSec or RestartSec from advanceArmed; tests wait for this interval to arm.

type Fire

type Fire struct {
	ActivationID string
	Name         string
	Unit         string
	Token        uint64 // identity of the arm that produced this event
}

Fire captures the source arm and target when a deadline is consumed.

type FireFunc

type FireFunc func(Fire)

FireFunc runs asynchronously without the engine lock held.

type Runtime

type Runtime struct {
	Activation     Activation
	LastScheduled  time.Time
	LastActual     time.Time
	LastSuccess    time.Time
	LastUnitActive time.Time
	FiredBoot      bool
	FiredStartup   bool
}

Runtime is per-activation and persistent timer state (DESIGN.md §17).

type Snapshot

type Snapshot struct {
	ScheduleState  string
	Activation     Activation
	StorageState   string
	StorageError   string
	ConfigRevision string
	Unit           string

	Next time.Time
	Last time.Time
}

Snapshot is next/last for status and list-timers.

type Spec

type Spec struct {
	ConfigRevision string // opaque identity supplied by the configuration owner

	Name string
	Unit string // activated unit; empty means same basename .service

	OnBootSec       time.Duration
	OnStartupSec    time.Duration
	OnUnitActiveSec time.Duration
	OnCalendar      []Calendar
	Persistent      bool

	OnBootSecSet       bool
	OnStartupSecSet    bool
	OnUnitActiveSecSet bool
}

Spec is one timer unit's schedule (DESIGN.md §17, §74).

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store persists last scheduled/actual/successful execution under <dir>/<name>.json (DESIGN.md §17, §32).

func OpenStore

func OpenStore(dir string) (*Store, error)

OpenStore creates dir if needed. An empty dir disables persistence.

func (*Store) Close

func (s *Store) Close() error

Close releases resources owned by the store. Load and Save open each file for one operation, so there is no retained handle to join.

func (*Store) Load

func (s *Store) Load(name string) Runtime

Load returns stored last-run times. Missing files yield a zero Runtime.

func (*Store) LoadChecked

func (s *Store) LoadChecked(name string) (Runtime, error)

LoadChecked distinguishes missing state from corrupt or unreadable state. Legacy unversioned timestamps are accepted and upgraded by the next save.

func (*Store) Save

func (s *Store) Save(name string, rt Runtime) error

Save writes last-run times. In-memory FiredBoot/FiredStartup are not stored: OnStartupSec is per winunitd instance; OnBootSec is recomputed from boot.

type Timer

type Timer interface {
	C() <-chan time.Time
	Stop() bool
	Reset(d time.Duration) bool
}

Timer is a one-shot wait that Clock can drive. A fake implementation fires due timers from Advance (issue #28, DESIGN.md §18).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL