scheduler

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package scheduler runs jobs that are due at most once and never catches up on missed runs (ADR-0008). It is Postgres-only.

A daily job runs at most once per Business date in Config.Location. It is due from local midnight plus NotBefore; missed dates are never run retroactively. Each run claims one scheduler_runs row per (job, business_date), and that claim upsert is the fence against duplicate runs.

An interval job runs on a fixed grid of multiples of Every on Unix time, so rollouts and restarts never shift it. Its scheduler_intervals row holds the next due_at, claimed with a conditional upsert; after an outage the job runs once and due_at jumps to the next grid point after now.

Leases (a leader lease plus one per job, under the namespace "<schema>.scheduler") only prevent duplicate work.

Tick(ctx, now) is the synchronous seam that runs everything due at now; Run(ctx) calls it in a loop. Jobs must be idempotent for the same date or grid point, since an aborted run (error, timeout or panic) is retried after Config.RetryAfter, or for interval jobs after min(RetryAfter, Every).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoLocation is returned by New when Config.Location is nil. There
	// is no UTC default: the business timezone must be chosen explicitly.
	ErrNoLocation = errors.New("scheduler: no location")
	// ErrInvalidConfig is returned by New when Config.Pool or Config.Claims
	// is missing.
	ErrInvalidConfig = errors.New("scheduler: invalid config")
	// ErrDuplicate is returned by Register for a job name that is already
	// registered.
	ErrDuplicate = errors.New("scheduler: duplicate job")
	// ErrInvalidJob is returned by Register for a job without a name or Run
	// func, with a negative duration, with NotBefore of a day or more, or
	// with NotBefore on an interval job.
	ErrInvalidJob = errors.New("scheduler: invalid job")
)
View Source
var ErrPanic = errors.New("scheduler: run panicked")

ErrPanic wraps the value of a panic that aborted a run.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Pool stores the runs. Required.
	Pool *pgxpool.Pool
	// Claims grants the leases; its Run must be running. Required.
	Claims *lease.Claims
	// Schema holds the scheduler tables. Defaults to "public".
	Schema string
	// Location is the business timezone that defines a Business date.
	// Required.
	Location *time.Location
	// RetryAfter is how long an aborted run waits before it is retried; an
	// interval job waits at most Every. Defaults to 5m.
	RetryAfter time.Duration
	// PollInterval is how often Run ticks. Defaults to 30s.
	PollInterval time.Duration
}

Config configures a Scheduler.

type Date

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date is a calendar date without a time or timezone, such as a Business date.

func DateOf

func DateOf(t time.Time) Date

DateOf returns the calendar date of t in t's location.

func (Date) String

func (d Date) String() string

String formats d as YYYY-MM-DD.

type Failure

type Failure struct {
	// Candidate identifies the failed candidate, such as a stream ID.
	Candidate string
	// Err is why it failed.
	Err error
}

Failure is one failed candidate of a run.

type Job

type Job struct {
	// Name identifies the job in the scheduler tables, leases and telemetry.
	Name string
	// Every is the interval of an interval job, whose runs are due at the
	// multiples of Every on Unix time; 0 makes a daily job.
	Every time.Duration
	// NotBefore delays a daily job past local midnight. It is added to the
	// midnight instant, so a run due inside a DST gap still runs. On a day
	// too short for it, the run is due NotBefore-24h before the next
	// midnight instead. It must be less than a day, and zero for interval
	// jobs.
	NotBefore time.Duration
	// Timeout bounds one run. Defaults to 30m.
	Timeout time.Duration
	// Run does the work. An error, a timeout or a panic aborts the run,
	// which is then retried; per-candidate failures belong in Outcome.
	Run func(ctx context.Context, run Run) (Outcome, error)
}

Job is a scheduled unit of work.

type Option

type Option func(*options)

Option configures a Scheduler beyond Config.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock Run ticks on. The default is time.Now.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger logs with logger instead of slog.Default().

func WithMeterProvider

func WithMeterProvider(mp metric.MeterProvider) Option

WithMeterProvider records metrics with mp instead of the global provider.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider records spans with tp instead of the global provider.

type Outcome

type Outcome struct {
	// Candidates is the number of candidates the run considered.
	Candidates int
	// Failures lists candidates that failed without aborting the run.
	Failures []Failure
}

Outcome reports what a finished run did.

type Run

type Run struct {
	// Date is the Business date the run is for. For an interval job it is
	// the Business date of Due.
	Date Date
	// Due is the instant the run became due. For an interval job it is the
	// grid point the run is for.
	Due time.Time
	// Location is the business timezone.
	Location *time.Location
	// Attempt counts the attempts for Date, starting at 1. For an interval
	// job it counts the attempts since the last successful run.
	Attempt int
}

Run describes one run of a job.

type Scheduler

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

Scheduler runs registered jobs when they are due.

func New

func New(cfg Config, opts ...Option) (*Scheduler, error)

New returns a Scheduler storing its runs through Config.Pool and taking its leases from Config.Claims. It fails with ErrNoLocation without a Location and with ErrInvalidConfig without Pool or Claims.

func (*Scheduler) Register

func (s *Scheduler) Register(job Job) error

Register adds job. It returns ErrDuplicate for a name that is already registered and ErrInvalidJob for an invalid job. Jobs registered while Run is running are picked up when Run starts again.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context) error

Run ticks every PollInterval until ctx ends, then releases the leader lease and returns nil. Each job ticks on its own, so a long run never delays another job. Jobs must be registered before Run is called.

func (*Scheduler) Tick

func (s *Scheduler) Tick(ctx context.Context, now time.Time) error

Tick runs every registered job that is due at now and waits for those runs to finish. A daily job is due once now has reached local midnight plus NotBefore on now's Business date and that date has no claimed run; earlier dates are never considered. An interval job is due once now has reached its next grid point; it then runs once for the latest grid point, however many were missed. Afterwards Tick keeps or takes the leader lease, whose holder reports the last_success gauge. Aborted runs are logged, not returned; Tick returns database and lease errors.

Jump to

Keyboard shortcuts

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