cron

package module
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 13 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cron

Go Reference CI

A fast, well-tested cron expression parser and job scheduler for Go.

This is a modernized fork of the abandoned robfig/cron/v3. It ships an idiomatic Go 1.26+ API with context.Context, log/slog, and a testable Clock interface.

Install

go get github.com/hyp3rd/cron/v4@latest

Quick start

package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"

    "github.com/hyp3rd/cron/v4"
)

func main() {
    c := cron.New()

    c.AddFunc("@every 5s", func(ctx context.Context) error {
        fmt.Println("tick")

        return nil
    })

    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()

    c.Start(context.Background())

    <-ctx.Done()
    c.Shutdown(context.Background())
}

Features

  • Standard 5-field cron expressions (minute, hour, dom, month, dow) plus optional seconds via WithSeconds().
  • Context-aware lifecycle — Start, Run, Stop, Shutdown, and every Job participate in cancellation and deadlines.
  • log/slog logging — structured, leveled logging out of the box. Default level is slog.LevelWarn to keep the scheduler quiet.
  • Clock interface — inject a fake clock via WithClock for deterministic, zero-time.Sleep tests.
  • Job wrappers — Recover, SkipIfStillRunning, DelayIfStillRunning, Timeout, MaxConcurrent, RetryOnError, and custom JobWrapper chains.
  • Defensive configuration — malformed TZ= / CRON_TZ= prefixes and invalid @every intervals return parse errors; nil With* options keep defaults.
  • Named entries — AddNamedFunc / AddNamedJob attach human-readable labels for logging and observability.
  • Event hooks — WithEventHooks for OnJobStart / OnJobComplete callbacks; WithOnError for error-only alerting.
  • Schedule inspection — NextN previews future fire times; SpecSchedule.String() round-trips a parsed schedule back to a cron expression.
  • Thread-safe — add, remove, and inspect entries while the scheduler is running.

Cron expressions

Field Allowed values Special characters
Minutes 0-59 * / , -
Hours 0-23 * / , -
Day of month 1-31 * / , - ?
Month 1-12 or JAN-DEC * / , -
Day of week 0-6 or SUN-SAT * / , - ?
Predefined schedules
Entry Equivalent
@yearly 0 0 1 1 *
@monthly 0 0 1 * *
@weekly 0 0 * * 0
@daily 0 0 * * *
@hourly 0 * * * *
Intervals
@every 1h30m

@every accepts positive time.ParseDuration values. Durations smaller than a second still round up to 1 second; @every 0s and negative durations are rejected as configuration errors.

Time zones
cron.New(cron.WithLocation(time.UTC))
// or per-schedule:
c.AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", myJob)

Malformed timezone prefixes such as CRON_TZ= or CRON_TZ=UTC without a schedule body return parse errors instead of panicking.

Lifecycle

Use Start(ctx) for a background scheduler and Run(ctx) for a blocking one. The context passed to Start or Run is also the parent context for every job.

  • Stop(ctx) cancels the scheduler and cancels contexts already handed to running jobs before waiting for them to return.
  • Shutdown(ctx) stops future scheduling and waits for running jobs to finish without cancelling their contexts.
  • If the Start / Run context is cancelled directly, both the scheduler and job contexts are cancelled.

Job wrappers / Chain

Panic recovery is available but not enabled by default. Install Recover explicitly if you want panics turned into logged ErrPanic errors:

c := cron.New(cron.WithChain(
    cron.Recover(logger),
    cron.SkipIfStillRunning(logger),
))

Or per-job:

wrapped := cron.NewChain(cron.Recover(logger)).Then(myJob)
Timeout, concurrency, and retries
c := cron.New(cron.WithChain(
    cron.Timeout(30 * time.Second),          // cancel after 30s
    cron.MaxConcurrent(3, logger),           // allow up to 3 in parallel
    cron.RetryOnError(2, 5 * time.Second),   // retry twice with 5s backoff
    cron.Recover(logger),
))

Named entries

c.AddNamedFunc("daily-report", "0 9 * * *", generateReport)

for _, e := range c.Entries() {
    fmt.Println(e.ID, e.Name, e.Next)
}

Event hooks

c := cron.New(cron.WithEventHooks(cron.EventHooks{
    OnJobStart: func(id cron.EntryID, name string) {
        span := tracer.Start(name)  // start a trace span
    },
    OnJobComplete: func(id cron.EntryID, name string, elapsed time.Duration, err error) {
        metrics.Observe(name, elapsed, err)  // record metrics
    },
}))

For error-only callbacks (alerting, retries):

c := cron.New(cron.WithOnError(func(id cron.EntryID, name string, err error) {
    alerting.Notify(name, err)
}))

Schedule inspection

// Preview the next 5 fire times
sched, _ := cron.ParseStandard("0 */6 * * *")
for _, t := range cron.NextN(sched, time.Now(), 5) {
    fmt.Println(t)
}

// Round-trip a parsed schedule back to a string
fmt.Println(sched) // "0 0,6,12,18 * * * *"

Testing with a fake clock

The Clock interface lets you drive the scheduler deterministically:

c := cron.New(cron.WithClock(fakeClock))

See clock.go for the interface definition.

Option defaults

Passing nil to WithLocation, WithParser, WithLogger, or WithClock keeps the package default instead of leaving the scheduler in an invalid state.

Migration from robfig/cron/v3

See MIGRATION.md for a step-by-step upgrade guide.

Changelog

See CHANGELOG.md.

License

MIT - see LICENSE.

Documentation

Overview

Package cron implements a cron spec parser and job runner.

Installation

To download the latest tagged release, run:

go get github.com/hyp3rd/cron/v4

Import it in your program as:

import "github.com/hyp3rd/cron/v4"

It requires Go 1.26 or later.

Usage

Callers may register Funcs to be invoked on a given schedule. Cron will run them in their own goroutines. All jobs receive a context.Context derived from the Cron.Start / Cron.Run context. That job context is cancelled when the parent context is cancelled or when Cron.Stop is called.

c := cron.New()
c.AddFunc("30 * * * *", func(ctx context.Context) error {
	fmt.Println("Every hour on the half hour")
	return nil
})
c.AddFunc("@hourly", func(ctx context.Context) error {
	fmt.Println("Every hour, starting an hour from now")
	return nil
})
c.Start(context.Background())
..
// Funcs are invoked in their own goroutine, asynchronously.
...
// Funcs may also be added to a running Cron
c.AddFunc("@daily", func(ctx context.Context) error {
	fmt.Println("Every day")
	return nil
})
..
// Inspect the cron job entries' next and previous run times.
inspect(c.Entries())
..
c.Stop(ctx)      // Cancel running jobs, then wait.
c.Shutdown(ctx)  // Graceful drain without cancelling running jobs.

Lifecycle

Cron exposes two shutdown modes:

  • Cron.Stop cancels the scheduler and the contexts already handed to running jobs, then waits for those jobs to return.
  • Cron.Shutdown stops future scheduling and waits for running jobs to finish without cancelling their contexts.

If the context passed to Cron.Start or Cron.Run is cancelled directly, both the scheduler and job contexts are cancelled.

CRON Expression Format

A cron expression represents a set of times, using 5 space-separated fields.

Field name   | Mandatory? | Allowed values  | Allowed special characters
----------   | ---------- | --------------  | --------------------------
Minutes      | Yes        | 0-59            | * / , -
Hours        | Yes        | 0-23            | * / , -
Day of month | Yes        | 1-31            | * / , - ?
Month        | Yes        | 1-12 or JAN-DEC | * / , -
Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?

Month and Day-of-week field values are case insensitive. "SUN", "Sun", and "sun" are equally accepted.

The specific interpretation of the format is based on the Cron Wikipedia page: https://en.wikipedia.org/wiki/Cron

Alternative Formats

Alternative Cron expression formats support other fields like seconds. You can implement that by creating a custom SpecParser as follows.

cron.New(
	cron.WithParser(
		cron.NewSpecParser(
			cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)))

Since adding Seconds is the most common modification to the standard cron spec, cron provides a builtin function to do that, which is equivalent to the custom parser you saw earlier, except that its seconds field is REQUIRED:

cron.New(cron.WithSeconds())

That emulates Quartz, the most popular alternative Cron schedule format: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

Special Characters

Asterisk ( * )

The asterisk indicates that the cron expression will match for all values of the field; e.g., using an asterisk in the 5th field (month) would indicate every month.

Slash ( / )

Slashes are used to describe increments of ranges. For example 3-59/15 in the 1st field (minutes) would indicate the 3rd minute of the hour and every 15 minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...", that is, an increment over the largest possible range of the field. The form "N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the increment until the end of that specific range. It does not wrap around.

Comma ( , )

Commas are used to separate items of a list. For example, using "MON,WED,FRI" in the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.

Hyphen ( - )

Hyphens are used to define ranges. For example, 9-17 would indicate every hour between 9am and 5pm inclusive.

Question mark ( ? )

Question mark may be used instead of '*' for leaving either day-of-month or day-of-week blank.

Predefined schedules

You may use one of several pre-defined schedules in place of a cron expression.

Entry                  | Description                                | Equivalent To
-----                  | -----------                                | -------------
@yearly (or @annually) | Run once a year, midnight, Jan. 1st        | 0 0 1 1 *
@monthly               | Run once a month, midnight, first of month | 0 0 1 * *
@weekly                | Run once a week, midnight between Sat/Sun  | 0 0 * * 0
@daily (or @midnight)  | Run once a day, midnight                   | 0 0 * * *
@hourly                | Run once an hour, beginning of hour        | 0 * * * *

Intervals

You may also schedule a job to execute at fixed intervals, starting at the time it's added or cron is run. This is supported by formatting the cron spec like this:

@every <duration>

where "duration" is a string accepted by time.ParseDuration (http://golang.org/pkg/time/#ParseDuration).

For example, "@every 1h30m10s" would indicate a schedule that activates after 1 hour, 30 minutes, 10 seconds, and then every interval after that.

Intervals must be greater than zero. Sub-second intervals are accepted and rounded up to one second.

Note: The interval does not take the job runtime into account. For example, if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes, it will have only 2 minutes of idle time between each run.

Time zones

By default, all interpretation and scheduling is done in the machine's local time zone (time.Local). You can specify a different time zone on construction:

cron.New(
    cron.WithLocation(time.UTC))

Individual cron schedules may also override the time zone they are to be interpreted in by providing an additional space-separated field at the beginning of the cron spec, of the form "CRON_TZ=Asia/Tokyo".

For example:

// Runs at 6am in time.Local
cron.New().AddFunc("0 6 * * ?", ...)

// Runs at 6am in America/New_York
nyc, _ := time.LoadLocation("America/New_York")
c := cron.New(cron.WithLocation(nyc))
c.AddFunc("0 6 * * ?", ...)

// Runs at 6am in Asia/Tokyo
cron.New().AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)

The prefix "TZ=(TIME ZONE)" is also supported for legacy compatibility.

Malformed timezone prefixes return parse errors rather than panicking.

Be aware that jobs scheduled during daylight-savings leap-ahead transitions will not be run!

Job Wrappers

A Cron runner may be configured with a chain of job wrappers to add cross-cutting functionality to all submitted jobs. For example, they may be used to achieve the following effects:

  • Recover panics from jobs by installing Recover
  • Delay a job's execution if the previous run hasn't completed yet
  • Skip a job's execution if the previous run hasn't completed yet
  • Log each job's invocations

Panic recovery is not enabled by default. To preserve scheduler availability when jobs may panic, install Recover explicitly via WithChain or NewChain.

Install wrappers for all jobs added to a cron using the WithChain option:

cron.New(cron.WithChain(
	cron.SkipIfStillRunning(logger),
))

Install wrappers for individual jobs by explicitly wrapping them:

job = cron.NewChain(
	cron.SkipIfStillRunning(logger),
).Then(job)

Additional built-in wrappers:

  • Timeout — cancels the job's context after a deadline
  • MaxConcurrent — allows up to N concurrent invocations (generalizes SkipIfStillRunning)
  • RetryOnError — retries failed jobs with configurable backoff

Wrapper ordering matters when composing. For example:

cron.NewChain(cron.Timeout(5*time.Second), cron.RetryOnError(3, time.Second)).Then(job)

gives each retry attempt its own 5-second timeout, while reversing the order shares a single timeout across all retries.

Named entries

Use Cron.AddNamedFunc, Cron.AddNamedJob, or Cron.ScheduleNamed to assign a human-readable name to an entry. The name appears in log messages, Entry.Name, and event hook callbacks.

Event hooks

Register lifecycle callbacks via WithEventHooks:

cron.New(cron.WithEventHooks(cron.EventHooks{
	OnJobStart:    func(id cron.EntryID, name string) { ... },
	OnJobComplete: func(id cron.EntryID, name string, elapsed time.Duration, err error) { ... },
}))

For error-only callbacks, use WithOnError:

cron.New(cron.WithOnError(func(id cron.EntryID, name string, err error) { ... }))

Schedule inspection

NextN previews the next N fire times for any Schedule:

times := cron.NextN(sched, time.Now(), 5)

SpecSchedule.String reconstructs a 6-field cron expression from a parsed schedule, enabling serialization and debugging.

Thread safety

Since the Cron service runs concurrently with the calling code, some amount of care must be taken to ensure proper synchronization.

All cron methods are designed to be correctly synchronized as long as the caller ensures that invocations have a clear happens-before ordering between them.

Logging

Cron uses log/slog for structured logging. By default, the scheduler logs at slog.LevelWarn and above, so routine scheduling events stay quiet. Pass a custom *slog.Logger via WithLogger to control log level and destination:

cron.New(
	cron.WithLogger(slog.New(
		slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
	)))

Option defaults

Passing nil to WithLocation, WithParser, WithLogger, or WithClock keeps the package default instead of leaving the scheduler in an invalid state.

Implementation

Cron entries are stored in an array, sorted by their next activation time. Cron sleeps until the next job is due to be run.

Upon waking:

  • it runs each entry that is active on that second
  • it calculates the next run times for the jobs that were run
  • it re-sorts the array of entries by next activation time.
  • it goes to sleep until the soonest job.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrAlreadyRunning = errors.New("cron: already running")

ErrAlreadyRunning is returned by Cron.Run when the scheduler is already running in another goroutine.

View Source
var ErrPanic = errors.New("cron: job panicked")

ErrPanic wraps a value recovered from a panicking job by Recover. Callers can use errors.Is to detect a recovered panic.

Functions

func DefaultLogger

func DefaultLogger() *slog.Logger

DefaultLogger is used by Cron if none is specified. It writes structured text to stdout under the "cron" group at slog.LevelWarn and above, so routine scheduling events stay quiet unless the caller opts in to verbose logging via WithLogger.

func DiscardLogger

func DiscardLogger() *slog.Logger

DiscardLogger can be used by callers to discard all log messages.

func NextN

func NextN(sched Schedule, after time.Time, count int) []time.Time

NextN returns the next n activation times for the given schedule, starting after the given time. If the schedule cannot produce n times (e.g., the schedule is unsatisfiable), the returned slice will have fewer than n elements.

Example
package main

import (
	"fmt"
	"time"

	"github.com/hyp3rd/cron/v4"
)

const (
	exampleEveryHour  = "0 * * * *"
	exampleNextNCount = 3
)

func main() {
	sched, _ := cron.ParseStandard(exampleEveryHour)

	//nolint:revive // example uses fixed date for deterministic output
	anchor := time.Date(2024, 6, 3, 12, 0, 0, 0, time.UTC)
	times := cron.NextN(sched, anchor, exampleNextNCount)

	for _, nextTime := range times {
		fmt.Println(nextTime.Format(time.DateTime))
	}

}
Output:
2024-06-03 13:00:00
2024-06-03 14:00:00
2024-06-03 15:00:00

Types

type Chain

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

Chain is a sequence of JobWrappers that decorates submitted jobs with cross-cutting behaviors like logging or synchronization.

func NewChain

func NewChain(c ...JobWrapper) Chain

NewChain returns a Chain consisting of the given JobWrappers.

func (Chain) Then

func (c Chain) Then(j Job) Job

Then decorates the given job with all JobWrappers in the chain.

This:

NewChain(m1, m2, m3).Then(job)

is equivalent to:

m1(m2(m3(job)))

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time
	// NewTimer creates a timer that fires after the given duration. The timer
	// must be stopped by the caller to release resources.
	NewTimer(d time.Duration) Timer
}

Clock abstracts the wall clock so that Cron can be driven by a fake clock in tests. The default clock returned by SystemClock delegates to the standard library time package.

func SystemClock

func SystemClock() Clock

SystemClock returns a Clock backed by time.Now and time.NewTimer. It is the default clock used by New when no WithClock option is supplied.

type ConstantDelaySchedule

type ConstantDelaySchedule struct {
	Delay time.Duration
}

ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". It does not support jobs more frequent than once a second.

func Every

func Every(duration time.Duration) ConstantDelaySchedule

Every returns a crontab Schedule that activates once every duration. Delays of less than a second are not supported (will round up to 1 second). Any fields less than a Second are truncated.

func (ConstantDelaySchedule) Next

func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time

Next returns the next time this should be run. This rounds so that the next activation time will be on the second.

type Cron

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

Cron keeps track of any number of entries, invoking the associated job as specified by the schedule. It may be started, stopped, and the entries may be inspected while running.

func New

func New(opts ...Option) *Cron

New returns a new Cron job runner, modified by the given options.

Available Settings

Time Zone
  Description: The time zone in which schedules are interpreted
  Default:     time.Local

Parser
  Description: Parser converts cron spec strings into cron.Schedules.
  Default:     Accepts this spec: https://en.wikipedia.org/wiki/Cron

Chain
  Description: Wrap submitted jobs to customize behavior.
  Default:     An empty chain; jobs are executed as-is.

Clock
  Description: Source of wall-clock time and timers used by the scheduler.
  Default:     A clock backed by time.Now / time.NewTimer.

See "cron.With*" to modify the default behavior.

func (*Cron) AddFunc

func (c *Cron) AddFunc(spec string, cmd func(ctx context.Context) error) (EntryID, error)

AddFunc adds a func to the Cron to be run on the given schedule. The spec is parsed using the time zone of this Cron instance as the default. An opaque ID is returned that can be used to later remove it.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

const exampleEverySecond = "* * * * * *"

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cronInstance := cron.New(cron.WithSeconds())
	cronInstance.AddFunc(exampleEverySecond, func(_ context.Context) error {
		fmt.Println("tick")
		cancel()

		return nil
	})

	cronInstance.Start(ctx)
	<-ctx.Done()

	cronInstance.Stop(context.Background())

}
Output:
tick

func (*Cron) AddJob

func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error)

AddJob adds a Job to the Cron to be run on the given schedule. The spec is parsed using the time zone of this Cron instance as the default. An opaque ID is returned that can be used to later remove it.

func (*Cron) AddNamedFunc

func (c *Cron) AddNamedFunc(name, spec string, cmd func(ctx context.Context) error) (EntryID, error)

AddNamedFunc is like Cron.AddFunc but assigns a human-readable name to the entry. The name appears in log messages, Entry.Name, and event hooks.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

const exampleEverySecond = "* * * * * *"

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cronInstance := cron.New(cron.WithSeconds())
	cronInstance.AddNamedFunc("heartbeat", exampleEverySecond, func(_ context.Context) error {
		fmt.Println("heartbeat")
		cancel()

		return nil
	})

	entry := cronInstance.Entries()[0]
	fmt.Println("name:", entry.Name)

	cronInstance.Start(ctx)
	<-ctx.Done()

	cronInstance.Stop(context.Background())

}
Output:
name: heartbeat
heartbeat

func (*Cron) AddNamedJob

func (c *Cron) AddNamedJob(name, spec string, cmd Job) (EntryID, error)

AddNamedJob is like Cron.AddJob but assigns a human-readable name to the entry. The name appears in log messages, Entry.Name, and event hooks.

func (*Cron) Entries

func (c *Cron) Entries() []Entry

Entries returns a snapshot of the cron entries.

func (*Cron) Entry

func (c *Cron) Entry(id EntryID) Entry

Entry returns a snapshot of the given entry, or the zero Entry if it could not be found.

func (*Cron) Location

func (c *Cron) Location() *time.Location

Location gets the time zone location.

func (*Cron) Remove

func (c *Cron) Remove(id EntryID)

Remove an entry from being run in the future.

func (*Cron) Run

func (c *Cron) Run(ctx context.Context) error

Run executes the scheduler synchronously on the calling goroutine until ctx is cancelled. It returns ErrAlreadyRunning if another goroutine is already running the scheduler.

func (*Cron) Schedule

func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID

Schedule adds a Job to the Cron to be run on the given schedule. The job is wrapped with the configured Chain.

func (*Cron) ScheduleNamed

func (c *Cron) ScheduleNamed(name string, schedule Schedule, cmd Job) EntryID

ScheduleNamed is like Cron.Schedule but assigns a human-readable name to the entry. The name appears in log messages, Entry.Name, and event hooks.

func (*Cron) Shutdown added in v4.0.1

func (c *Cron) Shutdown(ctx context.Context) error

Shutdown stops the scheduler and waits for in-flight jobs to finish without cancelling their contexts. The wait is bounded by the provided context. It returns ctx.Err() if the context is cancelled before all jobs complete.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

const exampleEverySecond = "* * * * * *"

func main() {
	cronInstance := cron.New(cron.WithSeconds())
	done := make(chan struct{})

	cronInstance.AddFunc(exampleEverySecond, func(_ context.Context) error {
		fmt.Println("tick")
		close(done)

		return nil
	})

	cronInstance.Start(context.Background())
	<-done

	cronInstance.Shutdown(context.Background())
	fmt.Println("graceful stop")

}
Output:
tick
graceful stop

func (*Cron) Start

func (c *Cron) Start(ctx context.Context)

Start launches the scheduler in its own goroutine bound to ctx. When ctx is cancelled the scheduler exits and running job contexts are cancelled. Calling Start on an already-running scheduler is a no-op.

func (*Cron) Stop

func (c *Cron) Stop(ctx context.Context) error

Stop cancels the running scheduler and the contexts already handed to in-flight jobs, then waits for those jobs to finish, bounded by the provided context. It returns ctx.Err() if the context is cancelled before all jobs complete. Calling Stop on a scheduler that is not running is a no-op and returns nil.

type Entry

type Entry struct {
	// ID is the cron-assigned ID of this entry, which may be used to look up a
	// snapshot or remove it.
	ID EntryID

	// Name is an optional human-readable label for this entry, useful for
	// logging, metrics, and debugging. It is set via [Cron.AddNamedFunc],
	// [Cron.AddNamedJob], or [Cron.ScheduleNamed].
	Name string

	// Schedule on which this job should be run.
	Schedule Schedule

	// Next time the job will run, or the zero time if Cron has not been
	// started or this entry's schedule is unsatisfiable.
	Next time.Time

	// Prev is the last time this job was run, or the zero time if never.
	Prev time.Time

	// Job is the job that was submitted to cron, kept around so callers can
	// recover it via [Cron.Entries] or [Cron.Entry].
	Job Job
	// contains filtered or unexported fields
}

Entry consists of a schedule and the job to execute on that schedule.

func (Entry) Valid

func (e Entry) Valid() bool

Valid returns true if this is not the zero entry.

type EntryID

type EntryID int

EntryID identifies an entry within a Cron instance.

type ErrorFunc

type ErrorFunc func(id EntryID, name string, err error)

ErrorFunc is called after a job returns a non-nil error. It fires in the job's goroutine, so it must be safe for concurrent use.

type EventHooks

type EventHooks struct {
	// OnJobStart is called just before a job begins execution.
	OnJobStart func(id EntryID, name string)

	// OnJobComplete is called after a job finishes, with the duration and
	// the error (or nil).
	OnJobComplete func(id EntryID, name string, elapsed time.Duration, err error)
}

EventHooks contains optional callbacks for job lifecycle events. All callbacks fire in the job's goroutine and must be safe for concurrent use.

type FuncJob

type FuncJob func(ctx context.Context) error

FuncJob adapts an ordinary function into a Job.

func (FuncJob) Run

func (f FuncJob) Run(ctx context.Context) error

Run executes the wrapped func.

type Job

type Job interface {
	Run(ctx context.Context) error
}

Job is the unit of work scheduled by Cron. Implementations should honor the provided context: when ctx is cancelled the job is expected to return promptly. Job contexts are cancelled when the parent Cron.Start / Cron.Run context is cancelled or when Cron.Stop is called. A non-nil error is logged by the scheduler but does not stop future executions.

type JobWrapper

type JobWrapper func(Job) Job

JobWrapper decorates the given Job with some behavior.

func DelayIfStillRunning

func DelayIfStillRunning(logger *slog.Logger) JobWrapper

DelayIfStillRunning serializes jobs, delaying subsequent runs until the previous one is complete. Jobs running after a delay of more than a minute have the delay logged at Info.

func MaxConcurrent

func MaxConcurrent(limit int, logger *slog.Logger) JobWrapper

MaxConcurrent allows up to limit concurrent invocations of the wrapped job. Additional invocations beyond the limit are skipped and logged at Info level. It generalizes SkipIfStillRunning, which is equivalent to MaxConcurrent with a limit of 1.

Example
package main

import (
	"context"
	"fmt"
	"log/slog"
	"os"

	"github.com/hyp3rd/cron/v4"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

	job := cron.NewChain(cron.MaxConcurrent(2, logger)).Then(
		cron.FuncJob(func(_ context.Context) error {
			fmt.Println("running")

			return nil
		}),
	)

	job.Run(context.Background())

}
Output:
running

func Recover

func Recover(logger *slog.Logger) JobWrapper

Recover converts panics in the wrapped job into a logged error. It is the recommended way to prevent a panicking job from tearing down the scheduler goroutine.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

func main() {
	job := cron.NewChain(cron.Recover(cron.DiscardLogger())).Then(
		cron.FuncJob(func(_ context.Context) error {
			panic("boom")
		}),
	)

	err := job.Run(context.Background())
	fmt.Println(errors.Is(err, cron.ErrPanic))

}
Output:
true

func RetryOnError

func RetryOnError(maxRetries int, backoff time.Duration) JobWrapper

RetryOnError retries the wrapped job up to maxRetries times when it returns a non-nil error. Between attempts it waits for the given backoff duration (or until the context is cancelled). A zero backoff retries immediately.

The backoff uses real wall-clock time, not the scheduler's Clock interface.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"sync/atomic"
	"time"

	"github.com/hyp3rd/cron/v4"
)

var errAttemptFailed = errors.New("attempt failed")

func main() {
	var attempts atomic.Int32

	job := cron.NewChain(cron.RetryOnError(2, time.Millisecond)).Then(
		cron.FuncJob(func(_ context.Context) error {
			attempt := attempts.Add(1)
			if attempt < 3 {
				return fmt.Errorf("%w: %d", errAttemptFailed, attempt)
			}

			fmt.Println("succeeded on attempt", attempt)

			return nil
		}),
	)

	job.Run(context.Background())

}
Output:
succeeded on attempt 3

func SkipIfStillRunning

func SkipIfStillRunning(logger *slog.Logger) JobWrapper

SkipIfStillRunning skips an invocation of the Job if a previous invocation is still running. It logs skips to the given logger at Info level.

func Timeout

func Timeout(duration time.Duration) JobWrapper

Timeout cancels the job's context after the given duration. If the job does not return before the deadline, the context passed to it is cancelled. The wrapper waits for the job to return and reports any error (including context.DeadlineExceeded) to the caller.

Note: the wrapper does not forcefully kill the job goroutine. The job must honor ctx.Done() for cancellation to take effect.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/hyp3rd/cron/v4"
)

func main() {
	job := cron.NewChain(cron.Timeout(5 * time.Second)).Then(
		cron.FuncJob(func(ctx context.Context) error {
			select {
			case <-ctx.Done():
				return ctx.Err()
			case <-time.After(time.Millisecond):
				fmt.Println("done")

				return nil
			}
		}),
	)

	job.Run(context.Background())

}
Output:
done

type Option

type Option func(*Cron)

Option represents a modification to the default behavior of a Cron.

func WithChain

func WithChain(wrappers ...JobWrapper) Option

WithChain specifies Job wrappers to apply to all jobs added to this cron. Refer to the Chain* functions in this package for provided wrappers.

func WithClock

func WithClock(clock Clock) Option

WithClock overrides the clock used by the cron instance. It is intended primarily for tests that want to drive the scheduler deterministically. Passing nil keeps the default system clock.

func WithEventHooks

func WithEventHooks(hooks EventHooks) Option

WithEventHooks registers lifecycle callbacks for job execution events.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/hyp3rd/cron/v4"
)

const exampleEverySecond = "* * * * * *"

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cronInstance := cron.New(
		cron.WithSeconds(),
		cron.WithEventHooks(cron.EventHooks{
			OnJobStart: func(id cron.EntryID, name string) {
				fmt.Printf("start: %s (id=%d)\n", name, id)
			},
			OnJobComplete: func(id cron.EntryID, name string, _ time.Duration, _ error) {
				fmt.Printf("complete: %s (id=%d)\n", name, id)
				cancel()
			},
		}),
	)

	cronInstance.AddNamedFunc("hello", exampleEverySecond, func(_ context.Context) error {
		return nil
	})

	cronInstance.Start(ctx)
	<-ctx.Done()

	cronInstance.Stop(context.Background())

}
Output:
start: hello (id=1)
complete: hello (id=1)

func WithLocation

func WithLocation(loc *time.Location) Option

WithLocation overrides the timezone of the cron instance. Passing nil keeps the default time.Local.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger uses the provided logger. Passing nil keeps the default logger.

func WithOnError

func WithOnError(fn ErrorFunc) Option

WithOnError registers a callback invoked whenever a job returns a non-nil error. The callback receives the entry's ID, name, and the error.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

const exampleEverySecond = "* * * * * *"

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cronInstance := cron.New(
		cron.WithSeconds(),
		cron.WithLogger(cron.DiscardLogger()),
		cron.WithOnError(func(id cron.EntryID, name string, err error) {
			fmt.Printf("error in %s (id=%d): %v\n", name, id, err)
			cancel()
		}),
	)

	cronInstance.AddNamedFunc("failing-job", exampleEverySecond, func(_ context.Context) error {
		return errors.New("something went wrong") //nolint:err113 // example error
	})

	cronInstance.Start(ctx)
	<-ctx.Done()

	cronInstance.Stop(context.Background())

}
Output:
error in failing-job (id=1): something went wrong

func WithParser

func WithParser(p Parser) Option

WithParser overrides the parser used for interpreting job schedules. Passing nil keeps the default parser.

func WithSeconds

func WithSeconds() Option

WithSeconds overrides the parser used for interpreting job schedules to include a seconds field as the first one.

type ParseOption

type ParseOption int

ParseOption represents configuration options for creating a parser. Most options specify which fields should be included, while others enable features. If a field is not included the parser will assume a default value. These options do not change the order fields are parse in.

const (
	// Second field, default 0.
	Second ParseOption = 1 << iota
	// SecondOptional seconds field, default 0.
	SecondOptional
	// Minute field, default 0.
	Minute
	// Hour field, default 0.
	Hour
	// Dom - Day of month field, default *.
	Dom
	// Month field, default *.
	Month
	// Dow - Day of week field, default *.
	Dow
	// DowOptional - Optional day of week field, default *.
	DowOptional
	// Descriptor - Allow descriptors such as @monthly, @weekly, etc.
	Descriptor
)

type Parser

type Parser interface {
	Parse(spec string) (Schedule, error)
}

Parser turns a cron spec string into a Schedule. The default implementation is SpecParser; callers can supply their own by passing WithParser.

type Schedule

type Schedule interface {
	// Next returns the next activation time, later than the given time.
	// Next is invoked initially, and then each time the job is run.
	Next(next time.Time) time.Time
}

Schedule describes a job's duty cycle.

func ParseStandard

func ParseStandard(standardSpec string) (Schedule, error)

ParseStandard returns a new crontab schedule representing the given standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries representing: minute, hour, day of month, month and day of week, in that order. It returns a descriptive error if the spec is not valid.

It accepts

  • Standard crontab specs, e.g. "* * * * ?"
  • Descriptors, e.g. "@midnight", "@every 1h30m"

type SpecParser

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

SpecParser that can be configured.

func NewSpecParser

func NewSpecParser(options ParseOption) SpecParser

NewSpecParser creates a SpecParser with custom options.

It panics if more than one Optional is given, since it would be impossible to correctly infer which optional is provided or missing in general.

Examples

// Standard parser without descriptors
specParser := NewSpecParser(Minute | Hour | Dom | Month | Dow)
sched, err := specParser.Parse("0 0 15 */3 *")

// Same as above, just excludes time fields
specParser := NewSpecParser(Dom | Month | Dow)
sched, err := specParser.Parse("15 */3 *")

// Same as above, just makes Dow optional
specParser := NewSpecParser(Dom | Month | DowOptional)
sched, err := specParser.Parse("15 */3")

func NewStandardParser

func NewStandardParser() SpecParser

NewStandardParser returns a SpecParser configured to parse standard 5-field crontab specs.

func (SpecParser) Parse

func (p SpecParser) Parse(spec string) (Schedule, error)

Parse returns a new crontab schedule representing the given spec. It returns a descriptive error if the spec is not valid. It accepts crontab specs and features configured by NewSpecParser.

type SpecSchedule

type SpecSchedule struct {
	Second, Minute, Hour, Dom, Month, Dow uint64

	// Override location for this schedule.
	Location *time.Location
}

SpecSchedule specifies a duty cycle (to the second granularity), based on a traditional crontab specification. It is computed initially and stored as bit sets.

func (*SpecSchedule) Next

func (s *SpecSchedule) Next(candidate time.Time) time.Time

Next returns the next time this schedule is activated, greater than the given time. If no time can be found to satisfy the schedule, return the zero time.

func (*SpecSchedule) String

func (s *SpecSchedule) String() string

String reconstructs a 6-field cron expression (second minute hour dom month dow) from the schedule's bit fields. If a field matches all values in its range the output is "*". The returned expression can be re-parsed by a SpecParser configured with Second.

Example
package main

import (
	"fmt"

	"github.com/hyp3rd/cron/v4"
)

func main() {
	parser := cron.NewSpecParser(
		cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
	)

	sched, _ := parser.Parse("*/5 * * * * *")
	fmt.Println(sched)

}
Output:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * *

type Timer

type Timer interface {
	// C returns the channel on which the fire event is delivered.
	C() <-chan time.Time
	// Stop prevents the timer from firing. It returns true if the call stops
	// the timer, or false if the timer has already expired or been stopped.
	Stop() bool
}

Timer is the subset of *time.Timer required by the scheduler loop. It exists so that fake clocks can drive the scheduler deterministically.

Jump to

Keyboard shortcuts

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