cron

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package cron is a tiny in-process recurring-job scheduler. Each job runs on an independent goroutine with a configurable interval, optional jitter, and panic recovery. For complex scheduling needs (cron expressions across instances, persistent queues, exactly-once) use temporal or a dedicated scheduler — this package is the boilerplate-killer for the common "every minute / every hour" workloads.

sched := cron.New(cron.WithLogger(log))
sched.Every(time.Minute, "cleanup-temp", func(ctx context.Context) error { ... })
sched.Every(5*time.Minute, "refresh-cache", func(ctx context.Context) error { ... })
sched.Start(ctx)
defer sched.Stop()

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadyStarted = errors.New("cron: scheduler already started")

ErrAlreadyStarted is returned when Start is called twice.

Functions

This section is empty.

Types

type JobFunc

type JobFunc func(ctx context.Context) error

JobFunc is a single execution of a recurring job.

type JobStats

type JobStats struct {
	Name      string
	Interval  time.Duration
	Runs      int64
	Failures  int64
	LastError string
}

JobStats is a point-in-time snapshot of a job's counters.

type Option

type Option func(*Scheduler)

func WithJitter

func WithJitter(frac float64) Option

WithJitter spreads job firing by up to `frac * interval` per run, to avoid thundering-herd patterns when many jobs share an interval. Default: 0.1 (10%).

func WithJobTimeout

func WithJobTimeout(d time.Duration) Option

WithJobTimeout caps how long any single job invocation can run. Default unset (no timeout — relies on Stop or ctx cancellation).

func WithLogger

func WithLogger(logf func(format string, args ...any)) Option

WithLogger wires a logging function called with job lifecycle events.

type Scheduler

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

Scheduler owns a set of recurring jobs.

func New

func New(opts ...Option) *Scheduler

New constructs a Scheduler.

func (*Scheduler) Every

func (s *Scheduler) Every(interval time.Duration, name string, fn JobFunc)

Every registers a recurring job. Panics if called after Start.

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context)

Start launches every registered job's loop. Returns immediately; the scheduler runs until ctx is cancelled or Stop is called.

func (*Scheduler) Stats

func (s *Scheduler) Stats() []JobStats

Stats reports per-job execution counters.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop signals all jobs to stop and waits for them to finish their current invocation. Safe to call multiple times.

Jump to

Keyboard shortcuts

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