A cron library for Go that implements a cron spec parser and job runner
npx @tessl/cli install tessl/golang-github-com-robfig-cron-v3@3.0.0A cron library for Go that implements a cron spec parser and job runner. This package enables developers to execute functions on a configurable schedule using standard cron expressions, with support for advanced features like timezone handling, job wrappers, and flexible parsing options.
go get github.com/robfig/cron/v3@v3.0.1import "github.com/robfig/cron/v3"import "github.com/robfig/cron/v3"package main
import (
"fmt"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
// Add functions to run on a schedule
c.AddFunc("30 * * * *", func() {
fmt.Println("Every hour on the half hour")
})
c.AddFunc("@hourly", func() {
fmt.Println("Every hour")
})
c.AddFunc("@every 1h30m", func() {
fmt.Println("Every hour thirty")
})
// Start the scheduler
c.Start()
// Stop when done
defer c.Stop()
// Keep main running...
select {}
}The cron scheduler manages a collection of entries, each consisting of a schedule and a job to execute. The scheduler runs in its own goroutine and executes jobs concurrently in separate goroutines when their schedules activate.
Key Components:
Create and manage the cron scheduler.
// New creates a new Cron job runner with optional configuration
func New(opts ...Option) *Cron
// Start begins the scheduler in its own goroutine
func (c *Cron) Start()
// Run starts the scheduler synchronously (blocking)
func (c *Cron) Run()
// Stop stops the scheduler and returns a context to wait for running jobs
func (c *Cron) Stop() context.ContextType Definitions:
type Cron struct {
// contains unexported fields
}Add, remove, and inspect scheduled jobs.
// AddFunc adds a function to run on the given schedule
func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error)
// AddJob adds a Job to run on the given schedule
func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error)
// Schedule adds a Job with a pre-parsed Schedule
func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID
// Remove removes an entry from future execution
func (c *Cron) Remove(id EntryID)
// Entries returns a snapshot of all cron entries
func (c *Cron) Entries() []Entry
// Entry returns a snapshot of a specific entry
func (c *Cron) Entry(id EntryID) Entry
// Location gets the time zone location
func (c *Cron) Location() *time.LocationType Definitions:
type EntryID int
type Entry struct {
ID EntryID
Schedule Schedule
Next time.Time
Prev time.Time
WrappedJob Job
Job Job
}
// Valid returns true if this is not the zero entry
func (e Entry) Valid() bool
type Job interface {
Run()
}
type FuncJob func()
func (f FuncJob) Run()Parse cron specification strings into Schedule objects.
// ParseStandard parses a standard 5-field cron spec
func ParseStandard(standardSpec string) (Schedule, error)
// NewParser creates a custom parser with specified fields
func NewParser(options ParseOption) Parser
// Parse parses a spec string into a Schedule
func (p Parser) Parse(spec string) (Schedule, error)Type Definitions:
type Schedule interface {
// Next returns the next activation time after the given time
Next(time.Time) time.Time
}
type ScheduleParser interface {
Parse(spec string) (Schedule, error)
}
type Parser struct {
// contains unexported fields
}
type ParseOption int
const (
Second ParseOption = 1 << iota // Seconds field, default 0
SecondOptional // Optional seconds field, default 0
Minute // Minutes field, default 0
Hour // Hours field, default 0
Dom // Day of month field, default *
Month // Month field, default *
Dow // Day of week field, default *
DowOptional // Optional day of week field, default *
Descriptor // Allow descriptors like @monthly, @weekly
)Built-in Schedule implementations for different scheduling patterns.
// SpecSchedule is a crontab-based schedule
type SpecSchedule struct {
Second uint64
Minute uint64
Hour uint64
Dom uint64
Month uint64
Dow uint64
Location *time.Location
}
func (s *SpecSchedule) Next(t time.Time) time.Time
// ConstantDelaySchedule is a simple recurring schedule
type ConstantDelaySchedule struct {
Delay time.Duration
}
func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time
// Every creates a schedule that activates once every duration
// Minimum duration is 1 second
func Every(duration time.Duration) ConstantDelayScheduleConfigure the Cron instance behavior on creation.
type Option func(*Cron)
// WithLocation sets the timezone for schedule interpretation
func WithLocation(loc *time.Location) Option
// WithSeconds enables parsing with a required seconds field
func WithSeconds() Option
// WithParser sets a custom parser for job schedules
func WithParser(p ScheduleParser) Option
// WithChain applies job wrappers to all jobs
func WithChain(wrappers ...JobWrapper) Option
// WithLogger sets a custom logger
func WithLogger(logger Logger) OptionAdd cross-cutting behavior to jobs using wrappers and chains.
type JobWrapper func(Job) Job
type Chain struct {
// contains unexported fields
}
// NewChain creates a Chain from the given JobWrappers
func NewChain(c ...JobWrapper) Chain
// Then decorates a job with all wrappers in the chain
func (c Chain) Then(j Job) Job
// Recover wraps jobs to recover from panics
func Recover(logger Logger) JobWrapper
// DelayIfStillRunning delays job execution if previous run hasn't finished
func DelayIfStillRunning(logger Logger) JobWrapper
// SkipIfStillRunning skips job execution if previous run is still running
func SkipIfStillRunning(logger Logger) JobWrapperConfigure logging for the cron scheduler.
type Logger interface {
// Info logs routine messages about cron's operation
Info(msg string, keysAndValues ...interface{})
// Error logs an error condition
Error(err error, msg string, keysAndValues ...interface{})
}
// DefaultLogger is used by Cron if none is specified
var DefaultLogger Logger
// DiscardLogger discards all log messages
var DiscardLogger Logger
// PrintfLogger wraps a Printf-based logger (errors only)
func PrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger
// VerbosePrintfLogger wraps a Printf-based logger (all messages)
func VerbosePrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger