scheduler

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 17 Imported by: 0

README

scheduler

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

scheduler is a code-defined application scheduler for Go services running on Kubernetes. Multiple scheduler replicas coordinate through fenced leases, while durable business work is dispatched to queue workers.

The module follows stable v1 compatibility. It does not claim exactly-once execution: leases reduce duplicate dispatch, and jobs must remain idempotent.

Requirements

  • Go 1.26.6 or later
  • PostgreSQL or Valkey 9 for multi-replica deployments
  • queue with a durable backend for long-running business work

Five-minute quickstart

schedule, err := scheduler.NewSchedule(
    "nightly-report",
    "reports.generate",
    scheduler.Daily(),
    scheduler.WithTimezone("Europe/Helsinki"),
    scheduler.WithOneServer(5*time.Minute),
)
if err != nil {
    return err
}

registry, err := scheduler.Compile(schedule)
if err != nil {
    return err
}

dispatcher, err := schedulerqueue.New(durableQueue)
if err != nil {
    return err
}

runner, err := scheduler.NewRunner(
    registry,
    postgresLeases,
    dispatcher,
    scheduler.WithOwner(podName),
)
if err != nil {
    return err
}

return runner.Run(ctx)

Compile the immutable registry during startup so invalid expressions, duplicate names, and unavailable time zones fail before the pod becomes ready. On shutdown, cancel Run and call Drain with a deadline.

Laravel-style frequency helpers are available as interval constructors and recurring constraints are schedule options:

schedule, err := scheduler.NewSchedule(
    "weekday-sync",
    "accounts.sync",
    scheduler.EveryTenMinutes(),
    scheduler.WithWeekdays(),
    scheduler.WithBetween("8:00", "17:00"),
    scheduler.WithTimezone("America/Chicago"),
)

Laravel-compatible execution controls compose with those options:

schedule, err := scheduler.NewSchedule(
    "weekday-sync",
    "accounts.sync",
    scheduler.Hourly(),
    scheduler.WithWeekdays(),
    scheduler.WithBetween("8:00", "17:00"),
    scheduler.WithTimezone("America/Chicago"),
    scheduler.WithoutOverlapping(10),
    scheduler.OnOneServer(),
    scheduler.RunInBackground(),
)

WithoutOverlapping() defaults to 1,440 minutes, while OnOneServer() uses an independent one-hour occurrence lease. The lease.Store supplied to NewRunner is the explicit equivalent of Laravel's useCache; all replicas must receive the same PostgreSQL or Valkey store. Use CLI clear-cache only after isolating any old executor that may still be performing side effects.

Custom cron expressions accept five fields or an optional leading seconds field. See the API reference for every frequency helper and its Laravel mapping.

Applications own pause and resume triggers instead of invoking scheduler commands. PauseState is suitable for one process; multi-replica deployments should supply a shared persistent implementation of the narrow interfaces:

pause := scheduler.NewPauseState()
runner, err := scheduler.NewRunner(
    registry,
    leases,
    executor,
    scheduler.WithOwner(podName),
    scheduler.WithPauseSource(pause),
)

// An authenticated endpoint, backpressure controller, or application command
// may call these idempotently.
_ = pause.Pause(ctx)
_ = pause.Resume(ctx)

Use EvenWhenPaused() only for operational schedules that must keep running. Cancel the context passed to Run, then call Drain, to implement an external deployment interrupt. Registry.Overview(after) provides deterministic list data, including next runs, for any caller-owned CLI, HTTP, or admin surface.

Packages

  • root: definitions, immutable registry, occurrences, runner, hooks, and events
  • cron: parser integration and explicit IANA time-zone compilation
  • lease, memory, postgres, valkey: fenced ownership contracts and stores
  • queue: queue occurrence envelopes
  • idempotency: optional idempotency dispatch guard
  • schedulerhttp, schedulercli: inspection and fenced recovery controls
  • schedulerservice: service lifecycle, drain ordering, and scheduled-work correlation composition
  • history: bounded operational event history
  • telemetry: log compatible structured logging and telemetry
  • schedulertest: deterministic fake clock

Documentation

Start with the documentation index, API reference, Laravel migration guide, and Kubernetes architecture. Release history is in CHANGELOG.md. Compilable integrations are in examples.

Security vulnerabilities should be reported through the private process in SECURITY.md. The project is available under the MIT License.

Development

Run make check. PostgreSQL and Valkey conformance require the environment variables described in CONTRIBUTING.md.

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

Documentation

Overview

Package scheduler defines code-based schedules and distributed execution.

Index

Constants

View Source
const (
	// DefaultOverlapTTL matches Laravel's default 1,440-minute event mutex.
	DefaultOverlapTTL = 24 * time.Hour
	// DefaultOneServerTTL matches Laravel's one-hour scheduling mutex.
	DefaultOneServerTTL = time.Hour
	// MaxJitter is the largest allowed deterministic schedule offset.
	MaxJitter = 24 * time.Hour
	// MaxIdentityBytes bounds schedule identity component strings.
	MaxIdentityBytes = 255
	// MaxExpressionBytes bounds a cron expression before parser invocation.
	MaxExpressionBytes = 1_024
	// MaxParameterBytes bounds the JSON-encoded task parameter payload.
	MaxParameterBytes = 64 << 10
	// MaxMetadataEntries bounds diagnostic metadata cardinality.
	MaxMetadataEntries = 128
	// MaxMetadataBytes bounds combined metadata key and value bytes.
	MaxMetadataBytes = 64 << 10
	// MaxEnvironments bounds environment filters per schedule.
	MaxEnvironments = 64
	// MaxConditions bounds trusted application conditions per schedule.
	MaxConditions = 32
	// MaxTimeWindows bounds recurring time constraints per schedule.
	MaxTimeWindows = 32
	// MaxCatchUp bounds retained delayed occurrences per decision.
	MaxCatchUp = 1_000
	// MaxSchedules bounds registry size before compilation.
	MaxSchedules = 10_000
)
View Source
const DefaultCallbackTimeout = time.Second

DefaultCallbackTimeout bounds conditions, hooks, and observers.

View Source
const DefaultLeaseOperationTimeout = 5 * time.Second

DefaultLeaseOperationTimeout bounds each distributed lease backend call.

View Source
const DefaultMaxConcurrentCallbacks = 128

DefaultMaxConcurrentCallbacks bounds active and timed-out callbacks.

View Source
const DefaultMaxConcurrentExecutions = 128

DefaultMaxConcurrentExecutions bounds managed in-process executions.

View Source
const MaxObservers = 128

MaxObservers bounds lifecycle observer registration per runner.

View Source
const MaxOccurrenceScan = 10_000

MaxOccurrenceScan bounds candidates inspected by one Due call.

Variables

View Source
var (
	// ErrInvalidExpression reports a schedule with invalid cron syntax.
	ErrInvalidExpression = errors.New("scheduler: invalid cron expression")
	// ErrInvalidTimezone reports a schedule with an unavailable IANA zone.
	ErrInvalidTimezone = errors.New("scheduler: invalid timezone")
	// ErrDuplicateSchedule reports repeated schedule names at compilation.
	ErrDuplicateSchedule = errors.New("scheduler: duplicate schedule")
	// ErrScheduleNotFound reports an unknown registry schedule name.
	ErrScheduleNotFound = errors.New("scheduler: schedule not found")
	// ErrOccurrenceLimit reports a due scan beyond its global candidate cap.
	ErrOccurrenceLimit = errors.New("scheduler: occurrence scan limit exceeded")
)
View Source
var (
	// ErrInvalidRunner reports missing or incompatible runner dependencies.
	ErrInvalidRunner = errors.New("scheduler: invalid runner dependencies")
	// ErrTaskPanic reports a recovered condition or executor panic.
	ErrTaskPanic = errors.New("scheduler: task panicked")
	// ErrDraining reports a new tick attempted after drain began.
	ErrDraining = errors.New("scheduler: runner is draining")
	// ErrUnsupportedHeartbeat reports a store unsafe for overlap leases.
	ErrUnsupportedHeartbeat = errors.New("scheduler: lease heartbeat is unsupported")
	// ErrUnsupportedOverlap reports unavailable safe replacement semantics.
	ErrUnsupportedOverlap = errors.New("scheduler: overlap replacement is unsupported")
	// ErrExecutionCapacity reports that the bounded executor pool is full.
	ErrExecutionCapacity = errors.New("scheduler: execution capacity exhausted")
	// ErrCallbackTimeout reports a condition or lifecycle callback deadline.
	ErrCallbackTimeout = errors.New("scheduler: callback timed out")
	// ErrCallbackCapacity reports that the bounded callback pool is full.
	ErrCallbackCapacity = errors.New("scheduler: callback capacity exhausted")
	// ErrPaused reports an occurrence skipped by application pause state.
	ErrPaused = errors.New("scheduler: paused")
)
View Source
var (
	// ErrScheduleNameRequired reports a blank schedule name.
	ErrScheduleNameRequired = errors.New("scheduler: schedule name is required")
	// ErrTaskNameRequired reports a blank task identity.
	ErrTaskNameRequired = errors.New("scheduler: task name is required")
	// ErrInvalidMissedRuns reports an invalid missed-run policy or bound.
	ErrInvalidMissedRuns = errors.New("scheduler: invalid missed-run policy")
	// ErrInvalidDateBounds reports an end instant before its start instant.
	ErrInvalidDateBounds = errors.New("scheduler: invalid date bounds")
	// ErrInvalidDuration reports a non-positive duration option.
	ErrInvalidDuration = errors.New("scheduler: duration must be positive")
	// ErrInvalidVersion reports a blank schedule version.
	ErrInvalidVersion = errors.New("scheduler: version is required")
	// ErrResourceLimit reports a definition beyond an exported safety budget.
	ErrResourceLimit = errors.New("scheduler: resource limit exceeded")
	// ErrInvalidConstraint reports an invalid recurring schedule constraint.
	ErrInvalidConstraint = errors.New("scheduler: invalid schedule constraint")
)

Functions

This section is empty.

Types

type Clock

type Clock interface {
	Now() time.Time
	After(time.Duration) <-chan time.Time
}

Clock provides current time and exact-boundary timers to a Runner.

type Condition

type Condition func(Context) (bool, error)

Condition allows trusted application code to permit an occurrence.

type Context

type Context struct {
	Schedule       Schedule
	Now            time.Time
	Due            time.Time
	Attempt        int
	Owner          string
	Fencing        uint64
	IdempotencyKey string
	Metadata       map[string]string
}

Context carries immutable schedule and ownership data to an Executor.

type Event

type Event struct {
	Type       EventType
	Result     Result
	Occurrence Occurrence
	Context    context.Context
	Owner      string
	Fencing    uint64
	At         time.Time
	Err        error
	Background bool
}

Event carries a bounded, structured scheduler lifecycle record.

type EventType

type EventType uint8

EventType identifies a scheduler lifecycle boundary.

const (
	// EventBefore is emitted immediately before execution.
	EventBefore EventType = iota
	// EventSuccess is emitted after successful execution.
	EventSuccess
	// EventFailure is emitted after a failed decision or execution.
	EventFailure
	// EventSkipped is emitted for a policy-based skip.
	EventSkipped
	// EventOverlap is emitted when an active overlap lease prevents execution.
	EventOverlap
	// EventCompleted terminates every emitted lifecycle.
	EventCompleted
	// EventFinished is emitted after a started executor returns.
	EventFinished
)

func (EventType) String

func (eventType EventType) String() string

type Executor

type Executor interface {
	Execute(context.Context, Context) error
}

Executor performs or dispatches one scheduled occurrence.

type Hook

type Hook func(Event)

Hook consumes a schedule lifecycle event.

type Hooks

type Hooks struct {
	Before    Hook
	Success   Hook
	Failure   Hook
	Skipped   Hook
	Overlap   Hook
	Completed Hook
	After     Hook
}

Hooks configures optional callbacks for each lifecycle boundary.

type Interval

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

Interval contains the explicit cron expression used by a schedule.

func At

func At(at string) Interval

At is an alias for DailyAt.

func Cron

func Cron(expression string) Interval

Cron constructs an interval from a five-field expression, an optional leading seconds field, an L day-of-month value, or a supported descriptor.

func Daily

func Daily() Interval

Daily returns the explicit daily cron interval.

func DailyAt

func DailyAt(at string) Interval

DailyAt returns a daily interval at the local HH:MM time.

func DaysOfMonth

func DaysOfMonth(days ...int) Interval

DaysOfMonth returns a midnight interval on each requested day of the month.

func EveryFifteenMinutes

func EveryFifteenMinutes() Interval

EveryFifteenMinutes returns an interval aligned to every minute divisible by fifteen.

func EveryFifteenSeconds

func EveryFifteenSeconds() Interval

EveryFifteenSeconds returns an interval aligned to every second divisible by fifteen.

func EveryFiveMinutes

func EveryFiveMinutes() Interval

EveryFiveMinutes returns an interval aligned to every minute divisible by five.

func EveryFiveSeconds

func EveryFiveSeconds() Interval

EveryFiveSeconds returns an interval aligned to every second divisible by five.

func EveryFourHours

func EveryFourHours(minutes ...int) Interval

EveryFourHours returns a four-hour interval at minute zero or the optional minute.

func EveryFourMinutes

func EveryFourMinutes() Interval

EveryFourMinutes returns an interval aligned to every minute divisible by four.

func EveryMinute

func EveryMinute() Interval

EveryMinute returns the explicit every-minute cron interval.

func EveryOddHour

func EveryOddHour(minutes ...int) Interval

EveryOddHour returns an odd-hour interval at minute zero or the optional minute.

func EverySecond

func EverySecond() Interval

EverySecond returns an interval aligned to every wall-clock second.

func EverySixHours

func EverySixHours(minutes ...int) Interval

EverySixHours returns a six-hour interval at minute zero or the optional minute.

func EveryTenMinutes

func EveryTenMinutes() Interval

EveryTenMinutes returns an interval aligned to every minute divisible by ten.

func EveryTenSeconds

func EveryTenSeconds() Interval

EveryTenSeconds returns an interval aligned to every second divisible by ten.

func EveryThirtyMinutes

func EveryThirtyMinutes() Interval

EveryThirtyMinutes returns an interval aligned to every minute divisible by thirty.

func EveryThirtySeconds

func EveryThirtySeconds() Interval

EveryThirtySeconds returns an interval aligned to every second divisible by thirty.

func EveryThreeHours

func EveryThreeHours(minutes ...int) Interval

EveryThreeHours returns a three-hour interval at minute zero or the optional minute.

func EveryThreeMinutes

func EveryThreeMinutes() Interval

EveryThreeMinutes returns an interval aligned to every minute divisible by three.

func EveryTwentySeconds

func EveryTwentySeconds() Interval

EveryTwentySeconds returns an interval aligned to every second divisible by twenty.

func EveryTwoHours

func EveryTwoHours(minutes ...int) Interval

EveryTwoHours returns a two-hour interval at minute zero or the optional minute.

func EveryTwoMinutes

func EveryTwoMinutes() Interval

EveryTwoMinutes returns an interval aligned to every minute divisible by two.

func EveryTwoSeconds

func EveryTwoSeconds() Interval

EveryTwoSeconds returns an interval aligned to every second divisible by two.

func Hourly

func Hourly() Interval

Hourly returns the explicit hourly cron interval.

func HourlyAt

func HourlyAt(minute int) Interval

HourlyAt returns an hourly interval at minute past each hour.

func LastDayOfMonth

func LastDayOfMonth(at string) Interval

LastDayOfMonth returns a monthly interval on the last day at the local HH:MM time.

func Monthly

func Monthly() Interval

Monthly returns the explicit first-day-at-midnight cron interval.

func MonthlyOn

func MonthlyOn(day int, at string) Interval

MonthlyOn returns a monthly interval on day at the local HH:MM time.

func Quarterly

func Quarterly() Interval

Quarterly returns a midnight interval on the first day of each quarter.

func QuarterlyOn

func QuarterlyOn(day int, at string) Interval

QuarterlyOn returns an interval on day of each quarter at the local HH:MM time.

func TwiceDaily

func TwiceDaily(firstHour, secondHour int) Interval

TwiceDaily returns a daily interval at both hours on minute zero.

func TwiceDailyAt

func TwiceDailyAt(firstHour, secondHour, minute int) Interval

TwiceDailyAt returns a daily interval at both hours on minute.

func TwiceMonthly

func TwiceMonthly(firstDay, secondDay int, at string) Interval

TwiceMonthly returns a monthly interval on both days at the local HH:MM time.

func Weekly

func Weekly() Interval

Weekly returns the explicit Sunday-at-midnight cron interval.

func WeeklyOn

func WeeklyOn(day time.Weekday, at string) Interval

WeeklyOn returns a weekly interval on day at the local HH:MM time.

func Yearly

func Yearly() Interval

Yearly returns a midnight interval on the first day of each year.

func YearlyOn

func YearlyOn(month time.Month, day int, at string) Interval

YearlyOn returns an annual interval on month and day at the local HH:MM time.

func (Interval) Expression

func (i Interval) Expression() string

Expression returns the exact cron expression represented by the interval.

type MaintenancePolicy

type MaintenancePolicy uint8

MaintenancePolicy controls execution while application maintenance is active.

const (
	// MaintenanceSkip suppresses execution during maintenance.
	MaintenanceSkip MaintenancePolicy = iota
	// MaintenanceRun allows execution during maintenance.
	MaintenanceRun
)

type MissedRunPolicy

type MissedRunPolicy uint8

MissedRunPolicy controls decisions after one or more delayed boundaries.

const (
	// MissedRunSkip executes only a boundary observed exactly on time.
	MissedRunSkip MissedRunPolicy = iota
	// MissedRunOnce executes only the newest missed boundary.
	MissedRunOnce
	// MissedRunCatchUp executes a bounded tail of missed boundaries.
	MissedRunCatchUp
)

type Observer

type Observer interface {
	Observe(Event)
}

Observer consumes scheduler lifecycle events.

type ObserverFunc

type ObserverFunc func(Event)

ObserverFunc adapts a function to Observer.

func (ObserverFunc) Observe

func (observe ObserverFunc) Observe(event Event)

Observe invokes the adapted observer function.

type Occurrence

type Occurrence struct {
	ScheduleID     string    `json:"schedule_id"`
	ScheduleName   string    `json:"schedule_name"`
	Task           string    `json:"task"`
	ScheduledAt    time.Time `json:"scheduled_at"`
	Attempt        int       `json:"attempt"`
	IdempotencyKey string    `json:"idempotency_key"`
}

Occurrence is one deterministic physical schedule boundary.

type Option

type Option func(*Schedule) error

Option configures a schedule before final validation and identity hashing.

func EvenWhenPaused

func EvenWhenPaused() Option

EvenWhenPaused allows this schedule to run while its runner is paused.

func OnOneServer

func OnOneServer() Option

OnOneServer enables a distributed occurrence lease with the default mutex TTL.

func RunInBackground

func RunInBackground() Option

RunInBackground allows the runner to continue starting other due tasks while this task executes. Drain still waits for the managed execution to finish; asynchronous results are reported through lifecycle hooks and observers.

func WithBetween

func WithBetween(start, end string) Option

WithBetween restricts occurrences to an inclusive recurring local-time window.

func WithCondition

func WithCondition(condition Condition) Option

WithCondition appends a non-nil trusted application condition.

func WithDateBounds

func WithDateBounds(start, end time.Time) Option

WithDateBounds limits occurrences to inclusive start and end instants.

func WithDays

func WithDays(days ...time.Weekday) Option

WithDays restricts occurrences to the requested local weekdays.

func WithEnabled

func WithEnabled(enabled bool) Option

WithEnabled controls whether the compiled schedule produces occurrences.

func WithEnvironments

func WithEnvironments(environments ...string) Option

WithEnvironments restricts execution to named application environments.

func WithFridays

func WithFridays() Option

WithFridays restricts occurrences to Friday.

func WithHooks

func WithHooks(hooks Hooks) Option

WithHooks sets lifecycle callbacks managed by the runner's callback bounds.

func WithJitter

func WithJitter(jitter time.Duration) Option

WithJitter sets the maximum deterministic per-schedule offset.

func WithMaintenancePolicy

func WithMaintenancePolicy(policy MaintenancePolicy) Option

WithMaintenancePolicy controls execution during application maintenance.

func WithMetadata

func WithMetadata(metadata map[string]string) Option

WithMetadata copies bounded diagnostic metadata into the schedule.

func WithMissedRuns

func WithMissedRuns(policy MissedRunPolicy, maxCatchUp int) Option

WithMissedRuns sets delayed-boundary behavior and its catch-up cap.

func WithMondays

func WithMondays() Option

WithMondays restricts occurrences to Monday.

func WithOneServer

func WithOneServer(ttl time.Duration) Option

WithOneServer enables a distributed occurrence lease with the given TTL.

func WithOverlap

func WithOverlap(policy OverlapPolicy) Option

WithOverlap records overlap policy without enabling a task lease.

func WithParameters

func WithParameters(parameters map[string]any) Option

WithParameters copies JSON-compatible task parameters into the schedule.

func WithRunTimeout

func WithRunTimeout(timeout time.Duration) Option

WithRunTimeout sets the execution deadline observed by the runner.

func WithSaturdays

func WithSaturdays() Option

WithSaturdays restricts occurrences to Saturday.

func WithSkip

func WithSkip(skip Condition) Option

WithSkip appends the inverse of a trusted application condition.

func WithSundays

func WithSundays() Option

WithSundays restricts occurrences to Sunday.

func WithThursdays

func WithThursdays() Option

WithThursdays restricts occurrences to Thursday.

func WithTimezone

func WithTimezone(timezone string) Option

WithTimezone sets the schedule's explicit IANA time-zone name.

func WithTuesdays

func WithTuesdays() Option

WithTuesdays restricts occurrences to Tuesday.

func WithUnlessBetween

func WithUnlessBetween(start, end string) Option

WithUnlessBetween excludes occurrences in an inclusive recurring local-time window.

func WithVersion

func WithVersion(version string) Option

WithVersion sets the semantic version included in schedule identity.

func WithWednesdays

func WithWednesdays() Option

WithWednesdays restricts occurrences to Wednesday.

func WithWeekdays

func WithWeekdays() Option

WithWeekdays restricts occurrences to Monday through Friday.

func WithWeekends

func WithWeekends() Option

WithWeekends restricts occurrences to Saturday and Sunday.

func WithoutOverlap

func WithoutOverlap(policy OverlapPolicy, ttl time.Duration) Option

WithoutOverlap enables a renewable task lease and overlap policy.

func WithoutOverlapping

func WithoutOverlapping(minutes ...int) Option

WithoutOverlapping skips an overlapping occurrence. The optional expiration is expressed in minutes and defaults to Laravel's 1,440-minute mutex TTL.

type OverlapPolicy

type OverlapPolicy uint8

OverlapPolicy controls a decision when the task lease is already held.

const (
	// OverlapAllow permits concurrent execution and does not acquire a task lease.
	OverlapAllow OverlapPolicy = iota
	// OverlapSkip skips an occurrence while its task lease is held.
	OverlapSkip
	// OverlapReplace delegates safe cancellation and transfer to a replacement store.
	OverlapReplace
)

type PauseController

type PauseController interface {
	Pause(context.Context) error
	Resume(context.Context) error
}

PauseController idempotently changes an application's scheduler pause state.

type PauseSource

type PauseSource interface {
	Paused(context.Context) (bool, error)
}

PauseSource reports whether ordinary schedules should be paused.

type PauseState

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

PauseState is a process-local, concurrency-safe pause source and controller. Distributed runners should use an application-owned shared persistent implementation of PauseSource and PauseController instead.

func NewPauseState

func NewPauseState() *PauseState

NewPauseState constructs an initially resumed process-local pause state.

func (*PauseState) Pause

func (state *PauseState) Pause(ctx context.Context) error

Pause idempotently pauses ordinary schedules.

func (*PauseState) Paused

func (state *PauseState) Paused(ctx context.Context) (bool, error)

Paused reports the current process-local pause state.

func (*PauseState) Resume

func (state *PauseState) Resume(ctx context.Context) error

Resume idempotently resumes ordinary schedules.

type Registry

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

Registry is an immutable compiled set of named schedules.

func Compile

func Compile(schedules ...Schedule) (*Registry, error)

Compile validates and freezes a complete named schedule set.

func (*Registry) ClearCache

func (registry *Registry) ClearCache(ctx context.Context, store lease.Store) (int, error)

ClearCache removes every currently observed task lease for schedules using overlap prevention. Each removal is fenced by the token returned by Inspect. Callers must first isolate active owners because lease removal cannot stop unfenced side effects already in progress.

func (*Registry) Due

func (registry *Registry) Due(name string, after, through time.Time) ([]Occurrence, error)

Due applies the schedule's bounded missed-run policy to an instant range.

func (*Registry) Next

func (registry *Registry) Next(name string, after time.Time) (time.Time, error)

Next returns the first occurrence strictly after an instant.

func (*Registry) Overview

func (registry *Registry) Overview(after time.Time) []ScheduleOverview

Overview returns immutable schedule definitions and their next boundaries, sorted by schedule name. Callers supply the reference instant so inspection remains deterministic and can be exposed through any application surface.

func (*Registry) Schedules

func (registry *Registry) Schedules() []Schedule

Schedules returns immutable copies sorted by schedule name.

type Result

type Result uint8

Result classifies the outcome of a schedule decision.

const (
	// ResultSucceeded reports successful execution or dispatch.
	ResultSucceeded Result = iota
	// ResultFailed reports a failed decision or execution.
	ResultFailed
	// ResultSkipped reports an intentional non-execution decision.
	ResultSkipped
)

func (Result) String

func (result Result) String() string

type Runner

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

Runner calculates due occurrences and coordinates their fenced execution.

func NewRunner

func NewRunner(registry *Registry, leases lease.Store, executor Executor, options ...RunnerOption) (*Runner, error)

NewRunner validates dependencies and distributed safety capabilities.

func (*Runner) Drain

func (runner *Runner) Drain(ctx context.Context) error

Drain rejects new ticks and waits for active decisions until ctx ends.

func (*Runner) Run

func (runner *Runner) Run(ctx context.Context) error

Run waits for exact schedule boundaries and processes due occurrences.

func (*Runner) RunFrom

func (runner *Runner) RunFrom(ctx context.Context, cursor time.Time) error

RunFrom processes the bounded missed-run window strictly after cursor, then continues waiting for exact schedule boundaries without leaving a startup gap. A zero cursor is rejected because it could request an unbounded scan.

func (*Runner) Tick

func (runner *Runner) Tick(ctx context.Context, after, through time.Time) error

Tick processes every bounded decision in an explicit instant range.

type RunnerOption

type RunnerOption func(*Runner) error

RunnerOption configures a Runner during construction.

func WithCallbackTimeout

func WithCallbackTimeout(timeout time.Duration) RunnerOption

WithCallbackTimeout bounds individual conditions, hooks, and observers.

func WithClock

func WithClock(clock Clock) RunnerOption

WithClock replaces wall time with an injectable scheduler clock.

func WithEnvironment

func WithEnvironment(environment string) RunnerOption

WithEnvironment selects schedules allowed in an application environment.

func WithHeartbeatInterval

func WithHeartbeatInterval(interval time.Duration) RunnerOption

WithHeartbeatInterval sets the renewal cadence for active task leases.

func WithLeaseOperationTimeout

func WithLeaseOperationTimeout(timeout time.Duration) RunnerOption

WithLeaseOperationTimeout bounds individual lease backend operations.

func WithMaintenanceMode

func WithMaintenanceMode(enabled bool) RunnerOption

WithMaintenanceMode controls maintenance-policy schedule filtering.

func WithMaxConcurrentCallbacks

func WithMaxConcurrentCallbacks(limit int) RunnerOption

WithMaxConcurrentCallbacks bounds active and timed-out callback goroutines.

func WithMaxConcurrentExecutions

func WithMaxConcurrentExecutions(limit int) RunnerOption

WithMaxConcurrentExecutions bounds active and timed-out managed executions.

func WithObserver

func WithObserver(observer Observer) RunnerOption

WithObserver appends a lifecycle observer when non-nil.

func WithOwner

func WithOwner(owner string) RunnerOption

WithOwner sets the unique identity used for lease ownership.

func WithPauseSource

func WithPauseSource(source PauseSource) RunnerOption

WithPauseSource supplies application-owned pause state. Lookup failures fail closed for ordinary schedules; EvenWhenPaused schedules do not consult it.

type Schedule

type Schedule struct {
	Name               string
	Version            string
	Task               string
	Expression         string
	Timezone           string
	Identity           string
	CoordinationID     string
	ParameterIdentity  string
	Parameters         map[string]any
	Enabled            bool
	Environments       []string
	DaysOfWeek         []time.Weekday
	TimeWindows        []TimeWindow
	MaintenancePolicy  MaintenancePolicy
	Conditions         []Condition
	StartAt            time.Time
	EndAt              time.Time
	Jitter             time.Duration
	Metadata           map[string]string
	MissedRunPolicy    MissedRunPolicy
	MaxCatchUp         int
	OverlapPolicy      OverlapPolicy
	OnOneServer        bool
	WithoutOverlapping bool
	LeaseTTL           time.Duration
	OneServerTTL       time.Duration
	OverlapTTL         time.Duration
	RunTimeout         time.Duration
	RunInBackground    bool
	Hooks              Hooks
	EvenWhenPaused     bool
}

Schedule is an immutable code-defined task timing and policy definition.

func NewSchedule

func NewSchedule(name, task string, interval Interval, options ...Option) (Schedule, error)

NewSchedule constructs, validates, bounds, and identifies a schedule.

type ScheduleOverview

type ScheduleOverview struct {
	Schedule Schedule
	Next     time.Time
}

ScheduleOverview combines an immutable schedule definition with its next enabled execution boundary. Next is zero for a disabled schedule.

type TimeWindow

type TimeWindow struct {
	Start    time.Duration `json:"start"`
	End      time.Duration `json:"end"`
	Excluded bool          `json:"excluded"`
}

TimeWindow is an inclusive recurring local-time constraint. Start and End are offsets since local midnight; Excluded inverts the allowed window.

Directories

Path Synopsis
Package cron compiles documented five- or six-field cron expressions in an explicit IANA time zone without exposing the underlying parser implementation.
Package cron compiles documented five- or six-field cron expressions in an explicit IANA time zone without exposing the underlying parser implementation.
examples
basic command
Command basic runs a single-process scheduler with an in-memory lease store.
Command basic runs a single-process scheduler with an in-memory lease store.
queue
Package queueexample demonstrates wiring durable queue dispatch into a scheduler runner.
Package queueexample demonstrates wiring durable queue dispatch into a scheduler runner.
Package history provides bounded in-memory scheduler event history.
Package history provides bounded in-memory scheduler event history.
Package idempotency integrates occurrence ownership with idempotency.
Package idempotency integrates occurrence ownership with idempotency.
Package lease defines distributed ownership and fencing contracts.
Package lease defines distributed ownership and fencing contracts.
conformance
Package conformance provides the shared lease-store contract suite.
Package conformance provides the shared lease-store contract suite.
Package memory provides a deterministic process-local lease store.
Package memory provides a deterministic process-local lease store.
Package postgres provides persistent server-time fenced leases.
Package postgres provides persistent server-time fenced leases.
Package queue dispatches schedule occurrences through queue.
Package queue dispatches schedule occurrences through queue.
Package schedulercli provides bounded scheduler inspection and recovery commands.
Package schedulercli provides bounded scheduler inspection and recovery commands.
Package schedulerhttp provides bounded scheduler inspection and recovery endpoints.
Package schedulerhttp provides bounded scheduler inspection and recovery endpoints.
Package schedulerservice composes a scheduler.Runner with the service lifecycle and correlation schedule semantics.
Package schedulerservice composes a scheduler.Runner with the service lifecycle and correlation schedule semantics.
Package schedulertest provides deterministic runner test utilities.
Package schedulertest provides deterministic runner test utilities.
Package telemetry records scheduler lifecycle logs, metrics, and traces.
Package telemetry records scheduler lifecycle logs, metrics, and traces.
Package valkey provides atomic fenced leases backed by Valkey 9 or newer.
Package valkey provides atomic fenced leases backed by Valkey 9 or newer.

Jump to

Keyboard shortcuts

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