scheduler

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package scheduler wraps robfig/cron/v3 for running periodic background jobs with panic-safe execution, per-job overlap policies, and observable statistics.

Scope: single-instance deployments. Distributed locking and multi-node coordination are intentionally out of scope.

Execution pipeline for cron-triggered jobs:

cron schedule -> Policy (Delay / Skip) -> Recover -> execute -> Job.Run

Policy is outer so it always observes a clean return from its wrapped chain and its internal bookkeeping (mutex unlock / channel refill) is never skipped by a panic. execute() additionally has its own defer recover so that RunNow (which bypasses the chain) is equally safe and so that panic is accounted for in statistics.

Index

Constants

This section is empty.

Variables

View Source
var ErrBusy = errors.New("scheduler: job busy")

ErrBusy signals that a Job refused to run because its own concurrency guard rejected the call (an instance is already in progress).

execute treats ErrBusy as neither success nor failure: RunCount and FailCount are unchanged, LastErr is not overwritten, and only a Debug log line is emitted. Return ErrBusy directly, or wrap it with fmt.Errorf("...: %w", ErrBusy); both forms are recognised via errors.Is.

View Source
var ErrPoolStopped = errors.New("pool: stopped")

ErrPoolStopped is returned by Submit when the Pool has been stopped.

Functions

This section is empty.

Types

type Entry

type Entry struct {
	Name      string    `json:"name"`
	Spec      string    `json:"spec"`
	Next      time.Time `json:"next"`
	LastStart time.Time `json:"last_start"`
	LastEnd   time.Time `json:"last_end"`
	LastErr   string    `json:"last_err"`
	RunCount  int64     `json:"run_count"`
	FailCount int64     `json:"fail_count"`
	AvgDurMs  int64     `json:"avg_dur_ms"`
}

Entry is an immutable snapshot of a Job's runtime state, intended for admin APIs and diagnostics.

type Job

type Job interface {
	Name() string
	Spec() string
	Policy() Policy
	Run(ctx context.Context) error
}

Job is the contract for anything registered with Scheduler.

Name must be unique within a Scheduler and is also the key for RunNow. Spec is any expression accepted by robfig/cron/v3 (e.g. "@every 1h", "0 */5 * * *"). Run must respect ctx cancellation; returning ErrBusy indicates "refused by internal guard" and is not counted as a failure.

type Policy

type Policy int

Policy controls how the scheduler handles a cron trigger that fires while a previous run of the same Job is still in progress.

const (
	// PolicyDelayIfRunning queues the new trigger until the previous run
	// finishes. Suitable for infrequent, must-not-skip tasks.
	PolicyDelayIfRunning Policy = iota

	// PolicySkipIfRunning drops the new trigger. Suitable for frequent
	// tasks where missing an occasional tick is acceptable.
	PolicySkipIfRunning
)

type Pool

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

Pool is a bounded worker pool for one-off async tasks. It fills the gap between cron-scheduled jobs (Scheduler) and unmanaged goroutines.

Submitted tasks run on a fixed set of worker goroutines. Panics are recovered and logged. Stop drains the queue and waits for in-flight tasks, integrating cleanly with the Component shutdown sequence.

func NewPool

func NewPool(opts PoolOptions) *Pool

NewPool creates a Pool but does not start workers. Call Start to begin processing. Intended to be wrapped by a PoolComponent that wires the lifecycle into the Registry.

func (*Pool) Start

func (p *Pool) Start(parent context.Context)

Start launches worker goroutines. The parent context is used to derive a cancellable context — Stop() cancels it, signalling workers to wind down after draining. Start is idempotent — the second call is a no-op.

func (*Pool) Stats

func (p *Pool) Stats() PoolStats

Stats returns a snapshot of pool runtime statistics.

func (*Pool) Stop

func (p *Pool) Stop(ctx context.Context) error

Stop signals workers to drain and waits for all in-flight tasks to complete. Stop is idempotent — the second call waits for the same drain without panicking. Returns ctx.Err() if the deadline is exceeded.

func (*Pool) Submit

func (p *Pool) Submit(ctx context.Context, t Task) (err error)

Submit enqueues a task for async execution. It blocks when the queue is full or returns an error when ctx is cancelled. Submit is safe to call from any goroutine. Returns ErrPoolStopped after Stop is called.

Uses recover to handle the inherent TOCTOU race between Submit and Stop: if Stop closes the channel between our check and the send, the panic is caught and converted to ErrPoolStopped.

func (*Pool) SubmitFunc

func (p *Pool) SubmitFunc(ctx context.Context, name string, fn func(context.Context) error) error

SubmitFunc is a convenience wrapper around Submit.

type PoolOptions

type PoolOptions struct {
	// Workers is the number of concurrent worker goroutines. Default 10.
	Workers int
	// QueueSize is the buffered channel capacity. When the queue is full,
	// Submit blocks until a slot opens or ctx is cancelled. Default 1000.
	QueueSize int
	// Logger receives task start/completion/error/panic events.
	Logger log.Logger
}

PoolOptions configures a Pool.

type PoolStats

type PoolStats struct {
	Submitted int64 `json:"submitted"`
	Completed int64 `json:"completed"`
	Failed    int64 `json:"failed"`
	Panicked  int64 `json:"panicked"`
	Pending   int   `json:"pending"` // current queue depth
	InFlight  int64 `json:"in_flight"`
}

PoolStats is a snapshot of pool runtime statistics.

type Scheduler

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

Scheduler runs registered Jobs on their cron schedules.

func New

func New(parent context.Context, logger log.Logger) *Scheduler

New constructs a Scheduler. The parent context governs job execution; Stop() cancels the derived root context, signalling all in-flight Run(ctx) invocations to wind down.

Uses the cron runner's default time zone (time.Local). Containerised deployments with TZ=UTC will see specs like "0 0 * * *" fire at UTC midnight; call NewWithLocation to pin an explicit zone.

func NewWithLocation

func NewWithLocation(parent context.Context, logger log.Logger, loc *time.Location) *Scheduler

NewWithLocation constructs a Scheduler with an explicit time.Location. All cron specs are interpreted in this zone. Typical use: a web app with users spread across zones picks a business zone (e.g. "America/ New_York") so operator-facing specs line up with invoices/reports.

func (*Scheduler) Entries

func (s *Scheduler) Entries() []Entry

Entries returns a snapshot of all registered Jobs' stats.

func (*Scheduler) Register

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

Register adds a Job. An invalid spec returns an error and leaves internal state untouched. Duplicate names are rejected.

func (*Scheduler) RunNow

func (s *Scheduler) RunNow(name string) error

RunNow synchronously executes the named Job once, outside the cron schedule. It respects the Job's Policy: with PolicySkipIfRunning, RunNow returns ErrBusy when a concurrent run is in progress; with PolicyDelayIfRunning, RunNow blocks until the in-flight run completes. Panic recovery and statistics bookkeeping match scheduled runs.

Returns the Job's error (or wrapped panic) if the run executed. When PolicySkipIfRunning rejects execution, returns ErrBusy (which is classified as "busy, not failure" and not counted in FailCount).

func (*Scheduler) Start

func (s *Scheduler) Start()

Start begins the cron loop. Call after all Register calls.

func (*Scheduler) Stop

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

Stop cancels the root context (signalling in-flight jobs) and waits for the cron to drain. Returns ctx.Err() wrapped if the shutdown context expires before all jobs finish.

type Task

type Task struct {
	// Name identifies the task in logs and metrics. Not required to be
	// unique — multiple tasks with the same name are allowed.
	Name string
	// Run executes the task. The context is cancelled when the Pool is
	// stopped; long-running tasks should check ctx.Done().
	Run func(ctx context.Context) error
}

Task is a named unit of work submitted to a Pool.

Jump to

Keyboard shortcuts

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