CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-robfig-cron-v3

A cron library for Go that implements a cron spec parser and job runner

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Cron - Job Scheduler for Go

A 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.

Package Information

  • Package Name: github.com/robfig/cron/v3
  • Package Type: Go module
  • Language: Go
  • Installation: go get github.com/robfig/cron/v3@v3.0.1
  • Import: import "github.com/robfig/cron/v3"

Core Imports

import "github.com/robfig/cron/v3"

Basic Usage

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 {}
}

Architecture

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:

  • Cron: Main scheduler that manages entries and executes jobs
  • Schedule: Interface defining when jobs should run
  • Job: Interface for executable tasks
  • Entry: Represents a scheduled job with its schedule and execution history
  • Parser: Converts cron spec strings into Schedule objects
  • Chain/JobWrapper: Decorates jobs with cross-cutting behaviors

Capabilities

Core Scheduler

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.Context

Type Definitions:

type Cron struct {
    // contains unexported fields
}

Core Scheduler

Job Management

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.Location

Type 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()

Job Management

Schedule Parsing

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
)

Schedule Parsing

Schedule Types

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) ConstantDelaySchedule

Schedule Types

Configuration Options

Configure 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) Option

Configuration Options

Job Wrappers

Add 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) JobWrapper

Job Wrappers

Logging

Configure 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

Logging

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/robfig/cron/v3@v3.0.1
Publish Source
CLI
Badge
tessl/golang-github-com-robfig-cron-v3 badge