cron

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 22 Imported by: 0

README

cronv5

Go Reference CI

A cron scheduler for Go, built for running jobs in production: every run has its own context, logger and history, and the scheduler handles daylight saving time, missed runs, concurrency and retries for you.

It started as a fork of robfig/cron and keeps its cron expression format, plus the Quartz L, W and # extensions.

c := cron.New().Build()
c.AddJob("0 9 * * MON-FRI", func(ctx context.Context) error {
	return sendReport(ctx) // cancelled on Stop, or when the run is cancelled
})
c.Start()

Features

  • Cron expressions: the standard 5 fields (an optional seconds field), @daily-style descriptors, @every 1h30m, Quartz L / W / # (0 0 L * *, 0 9 * * MON#1), wrapping ranges (FRI-MON), CRON_TZ= time zones, including UTC offsets (TZ=UTC+8).
  • Correct around daylight saving time: a job at a fixed time runs exactly once on transition days, like the Linux crontab (Vixie cron).
  • Jobs as plain functions: func(), func(context.Context) error, func(cron.JobRun)... The panics are recovered, and each run gets a context, a RunID and its own logger.
  • Scheduling: one-time jobs, run now (Trigger), misfire policies for runs missed while the machine was asleep or the cron was stopped, concurrency limits (global or per tag), retries with exponential backoff, timeouts, jitter.
  • Management: string IDs, labels and tags, enable / disable / update / remove at runtime, next and previous activation times.
  • Observability: hooks on job events, a metrics interface (Prometheus friendly), the history of the completed runs with their logs.
  • Graceful shutdown and a fake clock for your tests.

Installation

go get github.com/codeyu/cronv5

It requires Go 1.23 or newer. The package name is cron.

Quick start

package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"time"

	"github.com/codeyu/cronv5"
)

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

	// Every 5 minutes
	_, _ = c.AddJob("*/5 * * * *", func() {
		log.Println("tick")
	})

	// Every weekday at 9:00 in Tokyo, with a timeout
	_, err := c.AddJob("CRON_TZ=Asia/Tokyo 0 9 * * MON-FRI", cron.WithTimeout(time.Minute, func(ctx context.Context) error {
		return nil // the context is cancelled after one minute
	}), cron.Label("daily report"))
	if err != nil {
		log.Fatal(err) // invalid spec, or a spec that never activates (eg: "0 0 30 2 *")
	}

	c.Start()

	// Wait for Ctrl+C, then let the running jobs finish (up to 30s)
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	if err := c.Shutdown(shutdownCtx); err != nil {
		log.Println("some jobs were cancelled:", err)
	}
}

Cron expressions

Format
┌───────────── minute (0-59)
│ ┌─────────── hour (0-23)
│ │ ┌───────── day of month (1-31)
│ │ │ ┌─────── month (1-12 or JAN-DEC)
│ │ │ │ ┌───── day of week (0-7 or SUN-SAT, 0 and 7 are Sunday)
│ │ │ │ │
* * * * *

There is no seconds field by default. For jobs every few seconds, @every 10s works with the default format. To add a seconds field (0-59), in first position:

Builder 0 9 * * * (5 fields) 30 0 9 * * * (6 fields)
cron.New() (default) 9:00 every day error: expected exactly 5 fields
cron.New().WithOptionalSeconds() 9:00 every day 9:00:30 every day
cron.New().WithSeconds() ⚠️ minute 9 of every hour 9:00:30 every day

[!WARNING] With WithSeconds(), the seconds field is mandatory and the day of week becomes optional, so a 5 fields spec does not fail: it is read as second minute hour day-of-month month. When switching an existing cron to WithSeconds(), add a seconds field to all its specs, or use WithOptionalSeconds(), which reads 5 fields specs as before.

Names are case insensitive (MON, Mon, mon).

Character Fields Meaning Example
* all every value * * * * * every minute
, all list 0 8,12,18 * * * at 8:00, 12:00 and 18:00
- all range 0 9-17 * * * every hour from 9:00 to 17:00
/ all step */15 * * * * every 15 minutes, 5/15 at 5, 20, 35, 50
? day of month, day of week same as * 0 0 ? * MON
L day of month last day of the month, L-n: n days before it 0 0 L * *, 0 0 L-2 * *
W day of month weekday (Mon-Fri) nearest to the day, LW: last weekday 0 9 15W * *, 0 18 LW * *
L day of week last given day of the month 0 9 * * 5L (last Friday)
# day of week n-th given day of the month (1-5) 0 9 * * MON#1 (first Monday)

Ranges wrap around in the month and day of week fields: FRI-MON is Friday to Monday, NOV-FEB is November to February. When both the day of month and day of week are restricted, the schedule runs on days matching either one (as the crontab does): 0 0 1 * MON runs on the 1st and on Mondays.

AddJob rejects the specs that never activate, such as 0 0 30 2 * (February 30th), with ErrUnsatisfiableSchedule.

Examples
Spec Runs
0 * * * * every hour, on the hour
30 2 * * * every day at 2:30
0 9 * * MON-FRI weekdays at 9:00
0 0 1 * * the first day of every month at midnight
0 18 L * * the last day of every month at 18:00
0 18 LW * * the last weekday of every month at 18:00
0 10 * * MON#1 the first Monday of every month at 10:00
0 10 * * FRI-SUN Friday, Saturday and Sunday at 10:00
0 0 1 NOV-FEB * the first day of November, December, January and February
CRON_TZ=Europe/Paris 0 8 * * * every day at 8:00 in Paris
TZ=UTC+8 0 8 * * * every day at 8:00 UTC+8 (China, Singapore...)
Descriptors and intervals
Entry Equivalent to
@yearly (@annually) 0 0 1 1 *
@monthly 0 0 1 * *
@weekly 0 0 * * 0
@daily (@midnight) 0 0 * * *
@hourly 0 * * * *
@every <duration> every duration (@every 1h30m), starting when the job is added

For @every, use cron.RunOnStart to also run the job right away, or cron.WithNext(t) to choose the first run.

Time zones and daylight saving time

The specs are interpreted in the location of the cron (cron.New().WithLocation(loc), the machine's local time zone by default), or the one given by a CRON_TZ= (or TZ=) prefix: an IANA name (CRON_TZ=America/New_York) or a UTC offset (TZ=UTC+8, TZ=UTC-05:30, TZ=+0900). UTC+8 is 8 hours ahead of UTC, as in ISO 8601 (unlike the POSIX TZ variable and the IANA Etc/GMT+8 zone).

Daylight saving time transitions are handled like Vixie cron:

Fixed time spec (30 2 * * *) Interval spec (*/5 * * * *, 0 * * * *)
Clock jumps forward (2:00 → 3:00) runs once, at 3:00 skips the times that do not exist
Clock goes back (2:00 → 1:00) runs only the first time runs both times

A spec is an interval spec when its second, minute or hour field starts with *. Time zones without DST (UTC, Asia/Tokyo, Asia/Shanghai...) are not affected. To embed the tz database in your program instead of relying on the one of the machine, add import _ "time/tzdata".

Jobs

A job can be any of these functions, or a value with a Run method of one of these signatures, or a cron.Job:

func()
func() error
func(context.Context) error
func(cron.JobRun) error
func(context.Context, *cron.Cron, cron.JobRun) error
// ... and every combination of (context.Context, *cron.Cron, cron.EntryID | cron.Entry | cron.JobRun),
// with or without an error result: see the documentation of cron.J

Each run of a job is a JobRun, with a RunID, the Entry, its ScheduledAt time and its own logger: what a job logs with run.Logger() is kept with the run (see Job runs history). The context of a run is cancelled when the cron is stopped, when its entry is removed, with c.CancelJobRun(entryID, runID), and when the job completes. A job returning an error emits a JobErr event, a panic is recovered and emits a JobPanic event.

c.AddJob("0 * * * *", func(ctx context.Context, run cron.JobRun) error {
	run.Logger().Info("starting", "scheduledAt", run.ScheduledAt)
	return doWork(ctx)
}, cron.WithID("hourly-sync"), cron.Label("Sync the catalog"))
Job wrappers

Wrappers add behavior to a job, and can be combined (cron.Chain(job, w1, w2) is w2(w1(job))):

Wrapper Behavior
cron.WithTimeout(d, job) cancels the context after d
cron.WithDeadline(t, job) cancels the context at t
cron.WithRetry(n, job) retries up to n times (waits 1s, 2s, 3s...)
cron.WithRetryPolicy(policy, job) retries with exponential backoff, jitter, and a RetryIf predicate
cron.WithJitter(d, job) waits a random delay up to d before running
cron.Once(job) runs once, then removes the entry
cron.N(n, job) runs n times, then removes the entry
cron.SkipIfStillRunning(job) skips a run while the previous one is running (returns ErrJobAlreadyRunning)
cron.DelayIfStillRunning(job) waits for the previous run to complete
cron.ThresholdClb(d, job, clb) calls clb if the job ran longer than d
cron.ThresholdClbAsync(d, job, clb) calls clb as soon as the job runs longer than d

Each one also exists as a JobWrapper (TimeoutWrapper(d), RetryPolicyWrapper(policy)...), for Chain.

job := cron.WithRetryPolicy(cron.RetryPolicy{
	MaxRetries:   5,
	InitialDelay: time.Second, // 1s, 2s, 4s, 8s, 16s
	MaxDelay:     time.Minute,
	Jitter:       0.2, // ±20%
	RetryIf:      func(err error) bool { return !errors.Is(err, errInvalidInput) },
}, callAPI)
c.AddJob("*/10 * * * *", cron.WithTimeout(30*time.Second, job))

Managing entries

AddJob returns the EntryID of the entry. Options configure the entry when it is added:

Option Effect
cron.WithID(id) a chosen ID instead of a generated one
cron.Label(s) a description
cron.WithTags(tags...) tags, to manage entries by group or limit their concurrency
cron.RunOnStart also runs as soon as it is added (or the cron starts)
cron.WithNext(t) the first activation time
cron.Disabled added disabled
cron.NoOverlap skips an activation while the previous run is still running
cron.WithMisfirePolicy(p) what to do with missed activations (see below)
id, _ := c.AddJob("0 3 * * *", backup, cron.WithID("backup"), cron.WithTags("db", "nightly"))

runID, err := c.Trigger(id)           // run it now, its schedule is unchanged
err = c.Disable(id)                   // pause it, c.Enable(id) to resume
err = c.UpdateScheduleWithSpec(id, "0 4 * * *")
err = c.Remove(id)                    // cancels its running jobs too

c.DisableByTag("nightly")             // also EnableByTag, RemoveByTag, EntriesByTag
for _, entry := range c.Entries() {   // sorted by next activation time
	fmt.Println(entry.ID, entry.Label, entry.Next)
}
One-time jobs
// Runs once in 2 hours, then the entry is removed
c.AddJobAt(time.Now().Add(2*time.Hour), sendReminder, cron.Label("reminder"))

A time already past runs as soon as possible, including when the cron is started after it.

Activation times
next, _ := c.NextActivations(id, 5) // the next 5 runs of an entry, in the cron location

sched, _ := cron.ParseStandard("0 9 * * MON#1")
fmt.Println(cron.NextN(sched, time.Now(), 3))       // the next 3 activations
fmt.Println(sched.(*cron.SpecSchedule).Prev(time.Now())) // the previous one
for t := range cron.Activations(sched, time.Now()) { // all of them, until break
	if t.Year() > 2030 {
		break
	}
}

Reliability

Missed activations

An activation is missed when the cron was stopped at that time, or could not run it on time (eg: the machine was asleep). The misfire policy, for the cron (Builder.WithMisfirePolicy) or an entry (cron.WithMisfirePolicy), tells what to do:

Policy Missed while running Missed while stopped
MisfireDefault runs once skipped
MisfireSkip skipped (if later than the threshold) skipped (if later than the threshold)
MisfireRunOnce runs once runs once
MisfireRunAll each one runs (JobRun.ScheduledAt tells which) each one runs

The threshold of MisfireSkip is one minute (Builder.WithMisfireThreshold). Activations set explicitly (RunOnStart, WithNext, AddJobAt) are never skipped.

// Daily billing: if the server was down, catch up every missed day, one at a time
c.AddJob("0 1 * * *", cron.DelayIfStillRunning(bill), cron.WithMisfirePolicy(cron.MisfireRunAll))
Concurrency

By default, a job runs at each activation, even if its previous run is still running.

c := cron.New().
	WithMaxConcurrentJobs(10).           // at most 10 jobs at the same time
	WithTagConcurrencyLimit("db", 2).    // at most 2 jobs tagged "db"
	Build()
c.AddJob("*/5 * * * *", vacuum, cron.WithTags("db"), cron.NoOverlap) // and never twice at once

The runs over a limit wait for a slot (they can still be cancelled while waiting), the activations skipped by NoOverlap are reported to the metrics.

Stopping
Running jobs
<-c.Stop() their context is cancelled, the channel is closed once they returned
c.Shutdown(ctx) they can finish; if ctx is done first, they are cancelled and ctx.Err() is returned
cron.New().KeepJobsRunningOnStop() Stop waits for them without cancelling them

A stopped cron can be started again. c.Run() runs the scheduler in the current goroutine instead of c.Start().

Observability

Hooks

Hooks are called on job events (JobStart, JobCompleted, JobErr, JobPanic), for all the entries or one of them. They run in their own goroutine, unless cron.HookSync is given.

c.OnEvt(cron.JobErr, func(ctx context.Context, c *cron.Cron, hookID cron.HookID, run cron.JobRun) {
	alert(run.Entry.Label, run.Error)
})
c.OnEntryJobCompleted(id, func(ctx context.Context, c *cron.Cron, hookID cron.HookID, run cron.JobRun) {
	log.Println(run.Entry.ID, "completed, error:", run.Error)
}, cron.HookLabel("log completions"))
Metrics

Implement cron.Metrics (embed cron.BaseMetrics so that new methods do not break your type) and pass it to Builder.WithMetrics. For example, with Prometheus:

type promMetrics struct {
	cron.BaseMetrics
	runs     *prometheus.CounterVec   // labels: entry, result
	duration *prometheus.HistogramVec // labels: entry
	delay    *prometheus.HistogramVec // labels: entry
	skipped  *prometheus.CounterVec   // labels: entry, reason
}

func (m *promMetrics) JobStarted(run cron.JobRun, delay time.Duration) {
	m.delay.WithLabelValues(string(run.Entry.ID)).Observe(delay.Seconds())
}

func (m *promMetrics) JobCompleted(run cron.JobRun, duration time.Duration) {
	result := "ok"
	if run.Panic {
		result = "panic"
	} else if run.Error != nil {
		result = "error"
	}
	m.runs.WithLabelValues(string(run.Entry.ID), result).Inc()
	m.duration.WithLabelValues(string(run.Entry.ID)).Observe(duration.Seconds())
}

func (m *promMetrics) JobSkipped(entry cron.Entry, scheduledAt time.Time, reason cron.SkipReason) {
	m.skipped.WithLabelValues(string(entry.ID), reason.String()).Inc()
}

The methods are called synchronously, they must be fast. A panic in them is recovered and logged.

Job runs history
c := cron.New().
	WithKeepCompletedRunsDur(24 * time.Hour). // keep the completed runs for a day
	WithMaxCompletedRunsPerEntry(100).        // at most 100 per entry
	WithMaxLogSize(64 << 10).                 // at most 64 KiB of logs per run
	Build()

running := c.RunningJobs()
recent := c.RecentCompletedJobs(50)     // newest first
run, err := c.GetJobRun(entryID, runID) // with its Events, Error, Panic and Logs

The cron logs with log/slog by default (Builder.WithLogger, Builder.Quiet() to discard).

Testing your jobs

The cron accepts a fake clock (clockwork), so a test can run a schedule of hours in milliseconds:

func TestNightlyJob(t *testing.T) {
	clock := clockwork.NewFakeClockAt(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
	c := cron.New().WithClock(clock).WithLocation(time.UTC).Quiet().Build()
	done := make(chan struct{})
	c.AddJob("0 3 * * *", func() { close(done) })
	c.Start()
	defer c.Stop()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	if err := clock.BlockUntilContext(ctx, 1); err != nil { // the scheduler is waiting
		t.Fatal(err)
	}
	clock.Advance(3 * time.Hour)
	select {
	case <-done:
	case <-ctx.Done():
		t.Fatal("the job did not run at 3:00")
	}
}

Coming from robfig/cron

robfig/cron v3 cronv5
Create cron.New(cron.WithSeconds()) cron.New().WithSeconds().Build()
Optional seconds cron.WithParser(cron.NewParser(cron.SecondOptional | ...)) cron.New().WithOptionalSeconds()
Add a job c.AddFunc(spec, func()) c.AddJob(spec, func()) (and many other signatures)
Entry IDs int string, cron.WithID to choose it
Per run context, logger, history no yes
Panic recovery opt-in (cron.Recover) by default
Stop() does not stop running jobs cancels their context (Shutdown(ctx) for a graceful stop)
L, W, #, 7 as Sunday no yes
DST skips or runs twice runs once (Vixie cron)
Missed runs, concurrency limits, retries no yes
Hooks, metrics no yes

The cron expression format and the CRON_TZ= prefix are compatible.

Documentation

The API is stable since v1.0.0: the v1 releases only add features and fix bugs (Semantic Versioning).

Contributing

go test -race ./...

Issues and pull requests are welcome. Please add a test with every fix.

License

MIT, see LICENSE. Originally based on robfig/cron, copyright Rob Figueiredo.

Documentation

Overview

Package cron implements a cron spec parser and job runner.

Usage

Callers may register jobs to be invoked on a given schedule. Cron will run them in their own goroutines.

c := cron.New().Build()
_, _ = c.AddJob("30 * * * *", func() { fmt.Println("Every hour on the half hour") })
_, _ = c.AddJob("@hourly", func() { fmt.Println("Every hour") })
_, _ = c.AddJob("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
..
// Jobs are invoked in their own goroutine, asynchronously.
...
// Jobs may also be added to a running Cron
_, _ = c.AddJob("@daily", func() { fmt.Println("Every day") })
..
// Inspect the cron job entries' next and previous run times.
inspect(c.Entries())
..
<-c.Stop() // Stop the scheduler, cancel the context of the running jobs, and wait for them to complete.

AddJob accepts any function (or any type with a "Run" method) with a signature supported by J, for example: func(), func() error, func(context.Context) error, func(context.Context, cron.JobRun) error... AddFunc and AddJobStrict only accept the complete Job signature: func(context.Context, *cron.Cron, cron.JobRun) error.

Each run of a job receives a context that is cancelled when the run is cancelled (CancelJobRun), when the entry is removed, when the cron is stopped, or when the job completes.

Stopping

Stop stops the scheduler and returns a channel that is closed once all running jobs completed. By default, Stop cancels the context of the running jobs. Use the KeepJobsRunningOnStop builder option to let them complete, or Shutdown(ctx) for a graceful stop with a deadline:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := c.Shutdown(ctx); err != nil {
	// Some jobs were still running after 30s, their context has been cancelled.
}

A stopped cron can be started again. Entries whose next activation time went by while the cron was not running are rescheduled, instead of all running at once when the cron starts.

CRON Expression Format

A cron expression represents a set of times, using 5 space-separated fields. When the cron is built with WithSeconds, a mandatory seconds field is added in first position, and the day of week field becomes optional. A 5 fields spec is then read as "second minute hour day-of-month month": "0 9 * * *" is every hour at minute 9, not 9:00. WithOptionalSeconds accepts both: 5 fields specs without seconds ("0 9 * * *" is 9:00), and 6 fields specs with seconds first ("30 0 9 * * *" is 9:00:30).

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

Day of week 0 and 7 are both Sunday (Vixie cron numbering; note that Quartz uses 1 for Sunday).

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

Specs that never activate (eg: "0 0 30 2 *", February 30th) are rejected with ErrUnsatisfiableSchedule.

A custom parser can be configured with NewParser and the WithParser builder option.

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 4th 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.

In the month and day of week fields, a range can wrap around: "FRI-MON" is Friday, Saturday, Sunday and Monday, "NOV-FEB" is November to February. The other fields reject a range whose beginning is after its end.

Question mark ( ? )

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

L, W and # (day of month and day of week)

These items depend on the month, they can be combined with other items in a list (eg: "1,15,L"), but not in a range or with an increment.

Item   | Field        | Meaning
----   | -----        | -------
L      | Day of month | Last day of the month
L-n    | Day of month | n days before the last day of the month (0-30), eg: L-2
LW     | Day of month | Last weekday (Monday to Friday) of the month
nW     | Day of month | Weekday nearest to the n-th day of the month, eg: 15W
dL     | Day of week  | Last day d of the month, eg: 5L or FRIL (last Friday)
d#k    | Day of week  | k-th day d of the month (1-5), eg: MON#1 (first Monday)

"nW" never leaves the month: when the 1st is a Saturday, "1W" is Monday the 3rd, and when the 31st is a Sunday, "31W" is Friday the 29th. It does not activate in months that have no n-th day (eg: "31W" in April).

"L" alone in the day of week field is rejected, as its meaning differs between cron implementations: use 6 (or SAT) for Saturday, or 5L for the last Friday of the month.

As for other items, when both the day of month and day of week fields are restricted (neither is '*' or '?'), the schedule activates on days matching either one: "0 0 L * MON#1" activates on the first Monday and on the last day of every month.

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 * * * *

Missed activations

An activation is missed when the cron was not running at that time, or could not run the job on time (eg: the machine was sleeping). The misfire policy, set for the cron (Builder.WithMisfirePolicy) or for an entry (WithMisfirePolicy), tells what to do:

Policy          | Missed while running | Missed while not running
------          | -------------------- | ------------------------
MisfireDefault  | run once             | skipped
MisfireSkip     | skipped              | skipped
MisfireRunOnce  | run once             | run once
MisfireRunAll   | each one runs        | each one runs

MisfireSkip only skips the activations missed by more than the misfire threshold (Builder.WithMisfireThreshold, one minute by default). Activations explicitly set (RunOnStart, WithNext, AddJobAt) are never skipped. JobRun.ScheduledAt is the activation a run is for, and skipped activations are reported to Metrics.JobSkipped.

Concurrency

By default, a job runs at each activation even if its previous run is still running. The NoOverlap entry option skips the activations happening while a previous run is still running (reported to Metrics.JobSkipped). The number of jobs running at the same time can be limited for the whole cron (Builder.WithMaxConcurrentJobs) and for the entries having a tag (Builder.WithTagConcurrencyLimit): the runs over a limit wait for a running job to complete.

c := cron.New().WithMaxConcurrentJobs(10).WithTagConcurrencyLimit("db", 2).Build()
_, _ = c.AddJob("*\/5 * * * *", backup, cron.WithTags("db"), cron.NoOverlap)

One-time jobs

AddJobAt runs a job once, at a given time, then removes its entry:

id, err := c.AddJobAt(time.Now().Add(2*time.Hour), func() { ... })

A time already past runs as soon as possible, and a time that went by while the cron was not running runs when it starts. The At schedule (activating once) can also be used on its own.

Activation times

The activation times of a schedule can be listed without running it:

sched, _ := cron.ParseStandard("0 9 * * MON-FRI")
next5 := cron.NextN(sched, time.Now(), 5) // the next 5 activation times
for t := range cron.Activations(sched, time.Now()) {
	// successive activation times, until break
}
prev := sched.(*cron.SpecSchedule).Prev(time.Now()) // the last activation time

For an entry of a Cron, NextActivations lists the next activation times in the cron location, starting with the entry's next activation time:

times, err := c.NextActivations(id, 5)

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.

The first activation is one interval after the entry is added (if that time went by before the cron is started, see "Missed activations"). To run the job right away, then at every interval, use the RunOnStart entry option. To choose the first activation, use WithNext:

c.AddJob("@every 1h", job, cron.RunOnStart)                              // now, then every hour
c.AddJob("@every 1h", job, cron.WithNext(time.Now().Add(10*time.Minute))) // in 10 minutes, then every hour

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 time zone of the clock (the machine's local time zone). It can be changed with the WithLocation builder option, or at runtime with SetLocation.

A spec can also be prefixed with "CRON_TZ=<zone>" (or "TZ=<zone>") to use a specific time zone, for example "CRON_TZ=Asia/Tokyo 0 6 * * *". The zone can also be a UTC offset, such as "UTC+8", "UTC+05:30", "GMT-5" or "+0900": the offset is east of UTC, "UTC+8" is 8 hours ahead of UTC (as in ISO 8601, unlike the POSIX TZ variable and the IANA "Etc/GMT+8" zone, which is 8 hours behind UTC). A UTC offset has no daylight saving time.

The tz database of the machine is used (see time.LoadLocation). To embed it in the program instead, import the time/tzdata package:

import _ "time/tzdata"

Daylight saving time

Daylight saving time transitions are handled as Vixie cron (the Linux crontab) does. Schedules whose second, minute or hour field starts with '*' (eg: "*\/5 * * * *", "0 * * * *") are interval schedules, the other ones (eg: "30 2 * * *", "0 9 * * MON") run at a fixed time.

When the clock jumps forward (eg: from 2:00 to 3:00):

  • a fixed time schedule whose time is skipped runs once at the end of the jump (3:00);
  • an interval schedule skips the times that do not exist.

When the clock goes back (eg: from 2:00 to 1:00, 1:00-2:00 occurs twice):

  • a fixed time schedule whose time is repeated runs only the first time;
  • an interval schedule runs both times.

So "30 2 * * *" runs every day, once, and "0 * * * *" runs every hour of elapsed time. Time zones without daylight saving time (eg: UTC, Asia/Tokyo) are not affected.

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.

Implementation

Cron entries are stored in a min-heap, ordered 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 updates the position of these entries in the heap
  • it goes to sleep until the soonest job.
Example
c := cron.New().Quiet().Build()
_, _ = c.AddJob("30 * * * *", func() { fmt.Println("Every hour on the half hour") })
_, _ = c.AddJob("@hourly", func() { fmt.Println("Every hour") })
_, _ = c.AddJob("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
_, _ = c.AddJob("@daily", func() { fmt.Println("Every day") })
fmt.Println(len(c.Entries()))
<-c.Stop()
Output:
4

Index

Examples

Constants

View Source
const JobRunEventsBuffer = 100

JobRunEventsBuffer is the number of job runs buffered by the channels of JobRunCreatedCh and JobRunCompletedCh, before new ones are dropped.

Variables

View Source
var ErrCronNotRunning = errors.New("cron is not running")

ErrCronNotRunning is returned by Trigger when the cron is not running

View Source
var ErrEntryNotFound = errors.New("entry not found")

ErrEntryNotFound is returned when an entry ID does not exist

View Source
var ErrHookNotFound = errors.New("hook not found")

ErrHookNotFound is returned when a hook ID does not exist

View Source
var ErrIDAlreadyUsed = errors.New("id already used")

ErrIDAlreadyUsed is returned when adding an entry with the ID of an existing entry (see WithID)

View Source
var ErrJobAlreadyRunning = errors.New("job already running")

ErrJobAlreadyRunning is returned when a run is skipped because a previous run is still running (the SkipIfStillRunning wrapper, or Trigger on an entry with NoOverlap)

View Source
var ErrJobRunNotFound = errors.New("job run not found")

ErrJobRunNotFound is returned when a job run ID does not exist (or the completed run was cleaned up)

View Source
var ErrUnsatisfiableSchedule = errors.New("schedule never activates")

ErrUnsatisfiableSchedule is returned when a spec never activates (eg: "0 0 30 2 *", February 30th)

View Source
var ErrUnsupportedJobType = errors.New("unsupported job type")

ErrUnsupportedJobType is the panic value of J (and AddJob...) for a value that cannot be turned into a Job

SecondParser parses specs with a mandatory seconds field first, and an optional day of week field (see Builder.WithSeconds).

Functions

func Activations added in v1.0.0

func Activations(s Schedule, from time.Time) iter.Seq[time.Time]

Activations returns the successive activation times of the schedule after the given time (as computed by Next). The sequence ends if the schedule has no more activations, it is infinite otherwise: stop the iteration (break) once enough times are read.

for t := range cron.Activations(schedule, time.Now()) {
	if t.After(limit) {
		break
	}
	fmt.Println(t)
}

func Disabled

func Disabled(_ *Cron, entry *Entry)

Disabled adds the entry disabled, it does not run until it is enabled (see Enable)

func HookDisable

func HookDisable(hook *hookStruct)

HookDisable disables a hook by setting its active status to false.

func HookSync

func HookSync(hook *hookStruct)

HookSync makes the hook run synchronously.

func NextN added in v1.0.0

func NextN(s Schedule, from time.Time, n int) []time.Time

NextN returns the next n activation times of the schedule after the given time. It returns less than n times if the schedule has no more activations.

func NoOverlap added in v1.0.0

func NoOverlap(_ *Cron, entry *Entry)

NoOverlap skips the activations of the entry happening while a previous run of the entry is still running (including a run waiting for a concurrency limit). The skipped activations are reported to Metrics.JobSkipped, and Trigger returns ErrJobAlreadyRunning.

Unlike the SkipIfStillRunning job wrapper, no job run is created for a skipped activation.

func RunOnStart

func RunOnStart(c *Cron, entry *Entry)

RunOnStart runs the job as soon as the entry is added (or the cron is started), then on its schedule

Types

type AtSchedule added in v1.0.0

type AtSchedule struct {
	Time time.Time
}

AtSchedule is a schedule activating once, at a given time.

func At added in v1.0.0

func At(t time.Time) AtSchedule

At returns a schedule activating once, at the given time.

Added with Cron.Schedule, the entry stays after its activation (with no next activation time): use Cron.AddJobAt to run a job once and remove its entry.

func (AtSchedule) Next added in v1.0.0

func (s AtSchedule) Next(t time.Time) time.Time

Next returns the time of the schedule if it is after the given time, the zero time otherwise.

type BaseMetrics added in v1.0.0

type BaseMetrics struct{}

BaseMetrics implements Metrics with methods doing nothing, to embed in Metrics implementations.

func (BaseMetrics) JobCompleted added in v1.0.0

func (BaseMetrics) JobCompleted(JobRun, time.Duration)

JobCompleted does nothing

func (BaseMetrics) JobSkipped added in v1.0.0

func (BaseMetrics) JobSkipped(Entry, time.Time, SkipReason)

JobSkipped does nothing

func (BaseMetrics) JobStarted added in v1.0.0

func (BaseMetrics) JobStarted(JobRun, time.Duration)

JobStarted does nothing

type Builder

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

Builder provides a fluent interface for constructing a Cron instance with optional configuration. Use New() to create a builder, chain configuration methods, and call Build() to create the Cron instance.

func New

func New() *Builder

New creates a new Builder instance for constructing a Cron scheduler.

func (*Builder) Build

func (b *Builder) Build() *Cron

Build constructs and returns a configured Cron instance using the builder's settings. Default values are used for any unconfigured properties.

func (*Builder) KeepJobsRunningOnStop added in v0.2.0

func (b *Builder) KeepJobsRunningOnStop() *Builder

KeepJobsRunningOnStop makes Stop wait for the running jobs without cancelling their context. By default, Stop cancels the context of the running jobs.

func (*Builder) Quiet

func (b *Builder) Quiet() *Builder

Quiet configures the builder to discard all log output

func (*Builder) WithClock

func (b *Builder) WithClock(clock clockwork.Clock) *Builder

WithClock sets the clock implementation for the Cron instance.

func (*Builder) WithContext

func (b *Builder) WithContext(ctx context.Context) *Builder

WithContext sets the base context for the Cron instance.

func (*Builder) WithIDFactory

func (b *Builder) WithIDFactory(idFactory IDFactory) *Builder

WithIDFactory sets the ID generator factory for the Cron instance.

func (*Builder) WithJobRunLoggerFactory

func (b *Builder) WithJobRunLoggerFactory(jobRunLoggerFactory JobRunLoggerFactory) *Builder

WithJobRunLoggerFactory sets the logger factory for individual job runs.

func (*Builder) WithKeepCompletedRunsDur

func (b *Builder) WithKeepCompletedRunsDur(keepCompletedRunsDur time.Duration) *Builder

WithKeepCompletedRunsDur sets the duration to keep completed job runs before cleanup.

func (*Builder) WithLocation

func (b *Builder) WithLocation(loc *time.Location) *Builder

WithLocation sets the timezone location for the Cron instance.

func (*Builder) WithLogger

func (b *Builder) WithLogger(logger Logger) *Builder

WithLogger sets the logger for the Cron instance.

func (*Builder) WithMaxCompletedRunsPerEntry added in v0.2.0

func (b *Builder) WithMaxCompletedRunsPerEntry(n int) *Builder

WithMaxCompletedRunsPerEntry sets the maximum number of completed job runs kept per entry, the oldest ones are freed first. Completed job runs are kept if this option, or WithKeepCompletedRunsDur, is set.

func (*Builder) WithMaxConcurrentJobs added in v1.0.0

func (b *Builder) WithMaxConcurrentJobs(n int) *Builder

WithMaxConcurrentJobs limits the number of jobs running at the same time (0 = unlimited). The runs over the limit wait for a running job to complete (they are registered as running, see IsRunning), unless their context is cancelled (Stop, Remove, CancelJobRun...) while waiting.

func (*Builder) WithMaxLogSize added in v0.2.0

func (b *Builder) WithMaxLogSize(n int) *Builder

WithMaxLogSize sets the maximum size in bytes of the logs kept for each job run. When the limit is exceeded, the oldest logs are discarded.

func (*Builder) WithMetrics added in v1.0.0

func (b *Builder) WithMetrics(metrics Metrics) *Builder

WithMetrics sets the Metrics receiving the measurements of the job runs.

func (*Builder) WithMisfirePolicy added in v1.0.0

func (b *Builder) WithMisfirePolicy(policy MisfirePolicy) *Builder

WithMisfirePolicy sets the misfire policy of the entries using MisfireDefault (see MisfirePolicy).

func (*Builder) WithMisfireThreshold added in v1.0.0

func (b *Builder) WithMisfireThreshold(threshold time.Duration) *Builder

WithMisfireThreshold sets how late an activation must be to be missed, for the MisfireSkip policy (default: one minute).

func (*Builder) WithOptionalSeconds added in v1.0.0

func (b *Builder) WithOptionalSeconds() *Builder

WithOptionalSeconds configures the parser to accept an optional seconds field: a 5 fields spec is "minute hour day-of-month month day-of-week" as by default ("0 9 * * *" is 9:00), and a 6 fields spec has a seconds field first ("30 0 9 * * *" is 9:00:30).

func (*Builder) WithParser

func (b *Builder) WithParser(parser ScheduleParser) *Builder

WithParser sets the schedule parser for the Cron instance.

func (*Builder) WithSeconds

func (b *Builder) WithSeconds() *Builder

WithSeconds configures the parser to include seconds in the schedule specification: a mandatory seconds field comes first ("30 0 9 * * *" is 9:00:30), and the day of week field becomes optional.

Beware that a 5 fields spec is then read as "second minute hour day-of-month month": "0 9 * * *" is every hour at minute 9, not 9:00. To accept both 5 fields specs (without seconds) and 6 fields specs (with seconds), use WithOptionalSeconds.

func (*Builder) WithTagConcurrencyLimit added in v1.0.0

func (b *Builder) WithTagConcurrencyLimit(tag string, n int) *Builder

WithTagConcurrencyLimit limits the number of jobs of the entries having the tag (see WithTags) running at the same time (0 = unlimited). It can be set for several tags, a run of an entry having several limited tags waits until it is under all the limits. Runs over the limit wait, as with WithMaxConcurrentJobs.

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

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 func as specified by the schedule. It may be started, stopped, and the entries may be inspected while running.

func (*Cron) AddEntry

func (c *Cron) AddEntry(entry Entry, opts ...EntryOption) (EntryID, error)

AddEntry adds a pre-configured Entry to the Cron

func (*Cron) AddFunc

func (c *Cron) AddFunc(spec string, job FuncJob, opts ...EntryOption) (EntryID, error)

AddFunc adds a Job to the Cron to be run on the given schedule.

func (*Cron) AddJob

func (c *Cron) AddJob(spec string, job IntoJob, opts ...EntryOption) (EntryID, error)

AddJob adds a Job to the Cron to be run on the given schedule.

func (*Cron) AddJobAt added in v1.0.0

func (c *Cron) AddJobAt(at time.Time, job IntoJob, opts ...EntryOption) (EntryID, error)

AddJobAt adds a job run once, at the given time. The entry is removed when the job starts.

If the time is already past, the job runs as soon as possible (when the cron is running). It also runs when the cron is started, if its time went by while the cron was not running. An entry disabled (see Disable) when its time comes does not run, and stays until removed. It returns an error if the time is zero.

func (*Cron) AddJobStrict

func (c *Cron) AddJobStrict(spec string, job Job, opts ...EntryOption) (EntryID, error)

AddJobStrict same as AddJob, but only accept a Job interface instead of IntoJob (any)

func (*Cron) CancelJobRun

func (c *Cron) CancelJobRun(entryID EntryID, runID RunID) error

CancelJobRun attempts to cancel a running job by entry ID and run ID. Returns ErrEntryNotFound if the entry doesn't exist or ErrJobRunNotFound if the run doesn't exist.

func (*Cron) CleanupNow

func (c *Cron) CleanupNow()

CleanupNow triggers immediate cleanup of completed job runs

func (*Cron) CompletedJobRunsFor

func (c *Cron) CompletedJobRunsFor(entryID EntryID) ([]JobRun, error)

CompletedJobRunsFor returns all completed job runs for a specific entry. Returns ErrEntryNotFound if the entry doesn't exist.

func (*Cron) CompletedJobs

func (c *Cron) CompletedJobs() []JobRun

CompletedJobs returns a list of all completed job runs across all entries

func (*Cron) Disable

func (c *Cron) Disable(id EntryID) error

Disable deactivates a previously enabled cron entry by its ID (disabling an inactive entry does nothing). It returns ErrEntryNotFound if the entry does not exist.

func (*Cron) DisableByTag added in v1.0.0

func (c *Cron) DisableByTag(tag string) int

DisableByTag disables the entries having the given tag, and returns how many entries have the tag

func (*Cron) DisableHook

func (c *Cron) DisableHook(id HookID) error

DisableHook disables a previously enabled hook by its ID. It returns ErrHookNotFound if the hook does not exist.

func (*Cron) Enable

func (c *Cron) Enable(id EntryID) error

Enable activates a previously disabled cron entry by its ID (enabling an active entry does nothing). It returns ErrEntryNotFound if the entry does not exist.

func (*Cron) EnableByTag added in v1.0.0

func (c *Cron) EnableByTag(tag string) int

EnableByTag enables the entries having the given tag, and returns how many entries have the tag

func (*Cron) EnableHook

func (c *Cron) EnableHook(id HookID) error

EnableHook enables a previously disabled hook by its ID. It returns ErrHookNotFound if the hook does not exist.

func (*Cron) Entries

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

Entries returns a snapshot of the cron entries.

func (*Cron) EntriesByTag added in v1.0.0

func (c *Cron) EntriesByTag(tag string) []Entry

EntriesByTag returns a snapshot of the entries having the given tag, sorted like Entries

func (*Cron) Entry

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

Entry returns a snapshot of the given entry, or nil if it couldn't be found.

func (*Cron) GetCleanupTS

func (c *Cron) GetCleanupTS() time.Time

GetCleanupTS returns the timestamp of the last completed job runs cleanup

func (*Cron) GetHook

func (c *Cron) GetHook(id HookID) (Hook, error)

GetHook returns a specific hook by ID or ErrHookNotFound if not found

func (*Cron) GetHooks

func (c *Cron) GetHooks() []Hook

GetHooks returns all registered hooks (both global and entry-specific)

func (*Cron) GetJobRun

func (c *Cron) GetJobRun(entryID EntryID, runID RunID) (JobRun, error)

GetJobRun retrieves a specific job run by entry ID and run ID. Returns ErrEntryNotFound if the entry doesn't exist or ErrJobRunNotFound if the run doesn't exist.

func (*Cron) GetNextTime

func (c *Cron) GetNextTime() time.Time

GetNextTime returns the next time a job is scheduled to be executed If no job is scheduled to be executed, the Zero time is returned

func (*Cron) IsRunning

func (c *Cron) IsRunning(id EntryID) bool

IsRunning either or not a specific job is currently running

func (*Cron) JobRunCompletedCh

func (c *Cron) JobRunCompletedCh() <-chan JobRun

JobRunCompletedCh returns a channel receiving the job runs when they complete, with the same behavior as JobRunCreatedCh (to be notified of every job run, use OnJobCompleted).

func (*Cron) JobRunCreatedCh

func (c *Cron) JobRunCreatedCh() <-chan JobRun

JobRunCreatedCh returns a channel receiving the job runs when they are created (before they start).

The channel is created by the first call, the job runs created from then on are sent to it. It is buffered (JobRunEventsBuffer job runs): when it is full, because nobody receives from it or not fast enough, the new job runs are dropped, so that the jobs are never blocked by a slow receiver. All the calls return the same channel: with several receivers, each job run is received by one of them. To be notified of every job run, use hooks instead (OnJobStart, OnEvt...).

func (*Cron) Location

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

Location gets the time zone location

func (*Cron) NextActivations added in v1.0.0

func (c *Cron) NextActivations(id EntryID, n int) ([]time.Time, error)

NextActivations returns the next n times the entry will be activated, in the cron location, starting with the entry's next activation time (Entry.Next). It does not take into account whether the entry is active, or the job wrappers (eg: a job wrapped with Once runs only once).

func (*Cron) OnEntryEvt

func (c *Cron) OnEntryEvt(entryID EntryID, evt JobEventType, clb HookFn, opts ...HookOption) HookID

OnEntryEvt registers a hook function for a specific job event type on a specific entry. The hook will be called only when the specified event occurs for the given entry. Returns the HookID for later removal.

func (*Cron) OnEntryJobCompleted

func (c *Cron) OnEntryJobCompleted(entryID EntryID, clb HookFn, opts ...HookOption) HookID

OnEntryJobCompleted registers a hook function for job completion events on a specific entry. The hook will be called only when the given entry's job completes. Returns the HookID for later removal.

func (*Cron) OnEntryJobStart

func (c *Cron) OnEntryJobStart(entryID EntryID, clb HookFn, opts ...HookOption) HookID

OnEntryJobStart registers a hook function for job start events on a specific entry. The hook will be called only when the given entry's job starts. Returns the HookID for later removal.

func (*Cron) OnEvt

func (c *Cron) OnEvt(evt JobEventType, clb HookFn, opts ...HookOption) HookID

OnEvt registers a global hook function for a specific job event type. The hook will be called whenever the specified event occurs for any job. Returns the HookID for later removal.

func (*Cron) OnJobCompleted

func (c *Cron) OnJobCompleted(clb HookFn, opts ...HookOption) HookID

OnJobCompleted registers a global hook function for job completion events. The hook will be called whenever any job completes. Returns the HookID for later removal.

func (*Cron) OnJobStart

func (c *Cron) OnJobStart(clb HookFn, opts ...HookOption) HookID

OnJobStart registers a global hook function for job start events. The hook will be called whenever any job starts. Returns the HookID for later removal.

func (*Cron) RecentCompletedJobs added in v0.2.0

func (c *Cron) RecentCompletedJobs(limit int) []JobRun

RecentCompletedJobs returns the "limit" most recent completed job runs across all entries, newest first. Only the returned runs are exported, which is cheaper than CompletedJobs when many runs are kept. A limit <= 0 returns all the completed job runs.

func (*Cron) Remove

func (c *Cron) Remove(id EntryID) error

Remove an entry from being run in the future. Running jobs of the entry are cancelled, and the hooks specific to the entry are removed. It returns ErrEntryNotFound if the entry does not exist.

func (*Cron) RemoveByTag added in v1.0.0

func (c *Cron) RemoveByTag(tag string) int

RemoveByTag removes the entries having the given tag (as Remove does), and returns how many were removed

func (*Cron) RemoveHook

func (c *Cron) RemoveHook(id HookID) error

RemoveHook removes a previously registered hook by its HookID. Works for both global and entry-specific hooks. It returns ErrHookNotFound if the hook does not exist.

func (*Cron) Run

func (c *Cron) Run() (started bool)

Run the cron scheduler, or no-op if already running.

func (*Cron) RunNow

func (c *Cron) RunNow(id EntryID) error

RunNow runs the job of the entry now, as Trigger does, without returning the RunID.

If the cron is not running, the job runs as soon as the cron is started (unless the entry is disabled).

func (*Cron) RunningJobs

func (c *Cron) RunningJobs() []JobRun

RunningJobs returns a list of all currently running jobs across all entries

func (*Cron) RunningJobsFor

func (c *Cron) RunningJobsFor(entryID EntryID) ([]JobRun, error)

RunningJobsFor returns all currently running jobs for a specific entry // Returns ErrEntryNotFound if the entry doesn't exist.

func (*Cron) Schedule

func (c *Cron) Schedule(schedule Schedule, job Job, opts ...EntryOption) (EntryID, error)

Schedule adds a Job to the Cron to be run on the given schedule.

func (*Cron) SetCleanupInterval

func (c *Cron) SetCleanupInterval(dur time.Duration)

SetCleanupInterval sets the duration for keeping completed job runs before cleanup

func (*Cron) SetHookLabel

func (c *Cron) SetHookLabel(id HookID, label string) error

SetHookLabel sets a hook's label. It returns ErrHookNotFound if the hook does not exist.

func (*Cron) SetLocation

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

SetLocation sets a new location to use. Re-set the "Next" values for all entries. Re-sort entries and run due entries.

func (*Cron) SetTags added in v1.0.0

func (c *Cron) SetTags(id EntryID, tags ...string) error

SetTags replaces the tags of an entry. The concurrency limits of the tags (WithTagConcurrencyLimit) apply to the runs started after the change.

func (*Cron) Shutdown added in v0.2.0

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

Shutdown gracefully stops the cron: no new job is started, and it waits for the running jobs to complete without cancelling them. If ctx is done before, the context of the running jobs is cancelled and ctx.Err() is returned (without waiting for jobs that ignore their context).

Example
c := cron.New().Quiet().Build()
c.Start()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := c.Shutdown(ctx); err != nil {
	fmt.Println("some jobs were cancelled:", err)
}
fmt.Println("stopped")
Output:
stopped

func (*Cron) Start

func (c *Cron) Start() (started bool)

Start the cron scheduler in its own go-routine, or no-op if already started.

func (*Cron) Stop

func (c *Cron) Stop() <-chan struct{}

Stop stops the cron scheduler if it is running. A channel is returned so the caller can wait for running jobs to complete. The cron can be started again after being stopped.

func (*Cron) Trigger added in v1.0.0

func (c *Cron) Trigger(id EntryID) (RunID, error)

Trigger runs the job of the entry now, in addition to its schedule: the next activation time of the entry (Entry.Next) is not changed. The run is like a scheduled one: the job wrappers, hooks, events and panic recovery apply, and the run can be followed with its RunID (GetJobRun, CancelJobRun...). The run is started when Trigger returns.

Disabled entries are run too. It returns ErrCronNotRunning if the cron is not running, and ErrEntryNotFound if the entry does not exist.

func (*Cron) UpdateLabel

func (c *Cron) UpdateLabel(id EntryID, label string) error

UpdateLabel updates an entry's label. It returns ErrEntryNotFound if the entry does not exist.

func (*Cron) UpdateSchedule

func (c *Cron) UpdateSchedule(id EntryID, schedule Schedule) error

UpdateSchedule updates an entry's schedule with a new Schedule

func (*Cron) UpdateScheduleWithSpec

func (c *Cron) UpdateScheduleWithSpec(id EntryID, spec string) error

UpdateScheduleWithSpec updates an entry's schedule by parsing a spec string

func (*Cron) Wait

func (c *Cron) Wait()

Wait stops the cron and waits for all running jobs to complete before returning.

type Entry

type Entry struct {
	ID   EntryID
	Spec *string
	// The schedule on which this job should be run.
	Schedule Schedule
	// The next time the job will run. This is the zero time if Cron has not been started or this entry's schedule is unsatisfiable
	Next time.Time
	// The last time this job was run. This is the zero time if the job has never been run.
	Prev time.Time
	// Label to describe the job
	Label string
	// Tags of the entry (see WithTags), to query or manage entries by group
	Tags []string
	// Skip the activations happening while a previous run of the entry is still running (see NoOverlap)
	NoOverlap bool
	// What to do with the activations missed by more than the misfire threshold (see WithMisfirePolicy).
	// MisfireDefault uses the policy of the cron.
	MisfirePolicy MisfirePolicy
	// Either or not the job is currently active
	Active bool
	// contains filtered or unexported fields
}

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

func (Entry) HasTag added in v1.0.0

func (e Entry) HasTag(tag string) bool

HasTag returns true if the entry has the given tag

func (Entry) Job

func (e Entry) Job() any

Job returns the job given to AddJob (for a function, the function itself, before it was adapted to the Job interface).

Calling it directly bypasses the cron: no job run (RunID, logger), hooks, events nor panic recovery. Use Cron.Trigger (or RunNow) to run the job now as the cron does.

type EntryID

type EntryID ID

EntryID identifies a cron entry

type EntryOption

type EntryOption func(*Cron, *Entry)

EntryOption configures an entry when it is added (AddJob, Schedule, AddJobAt...)

func Label

func Label(label string) EntryOption

Label sets the label of the entry, to describe it (see UpdateLabel)

func WithID

func WithID(id EntryID) EntryOption

WithID sets the ID of the entry, instead of a generated one (AddJob returns ErrIDAlreadyUsed if it is used)

func WithMisfirePolicy added in v1.0.0

func WithMisfirePolicy(policy MisfirePolicy) EntryOption

WithMisfirePolicy sets the misfire policy of the entry (see MisfirePolicy). Activations explicitly set (RunOnStart, WithNext, AddJobAt, RunNow before Start) are never skipped.

func WithNext

func WithNext(next time.Time) EntryOption

WithNext sets the first activation time of the entry, the schedule is used for the next ones. The time is kept if the cron is started after it: the job then runs when the cron starts.

func WithTags added in v1.0.0

func WithTags(tags ...string) EntryOption

WithTags adds tags to the entry, to query or manage entries by group (EntriesByTag, RemoveByTag, EnableByTag, DisableByTag) or to limit their concurrency (WithTagConcurrencyLimit). Duplicated and empty tags are ignored.

type FuncIDFactory

type FuncIDFactory func() ID

FuncIDFactory is a function type that generates a new unique ID. It implements the IDFactory interface by providing a Next() method.

func (FuncIDFactory) Next

func (f FuncIDFactory) Next() ID

Next implements the IDFactory interface for FuncIDFactory. It calls the underlying function to generate and return a new ID.

type FuncJob

type FuncJob func(context.Context, *Cron, JobRun) error

FuncJob is a wrapper that turns a func() into a cron.Job

func (FuncJob) Run

func (f FuncJob) Run(ctx context.Context, c *Cron, r JobRun) error

type FuncJobRunLoggerFactory

type FuncJobRunLoggerFactory func(w io.Writer) Logger

FuncJobRunLoggerFactory is a function type that implements JobRunLoggerFactory. It allows any function with the signature func(w io.Writer) *slog.Logger to be used as a JobRunLoggerFactory.

func (FuncJobRunLoggerFactory) New

New implements the JobRunLoggerFactory interface for FuncJobRunLoggerFactory. It simply calls the underlying function with the provided writer.

type Hook

type Hook struct {
	ID        HookID       // Unique identifier for the hook
	EntryID   *EntryID     // Associated job entry ID (nil if global)
	EventType JobEventType // Type of job event that triggers this hook
	Active    bool         // Whether the hook is currently active
	Async     bool         // Whether the hook runs asynchronously
	Label     string       // Human-readable label for the hook
}

Hook represents a configured cron job hook with its properties.

type HookFn

type HookFn func(context.Context, *Cron, HookID, JobRun)

HookFn is a function type for cron job hooks.

type HookID

type HookID ID

HookID is a unique identifier for a cron job hook.

type HookOption

type HookOption func(*hookStruct)

HookOption is a function type for configuring a hook.

func HookLabel

func HookLabel(label string) HookOption

HookLabel returns a HookOption that sets the label for a hook.

type ID

type ID string

ID is the type to use for all internal IDs (EntryID, RunID, HookID)

type IDFactory

type IDFactory interface {
	// Next generates and returns a new unique ID.
	// Implementations must ensure IDs are unique across calls.
	Next() ID
}

IDFactory is an interface for types that can generate unique IDs. Implementations should provide thread-safe ID generation.

func UuidIDFactory

func UuidIDFactory() IDFactory

UuidIDFactory generate and format UUID V4

type IntoJob

type IntoJob any

IntoJob is something that can be cast into a Job. See the J helper documentation for all accepted function signatures.

type Job

type Job interface {
	Run(context.Context, *Cron, JobRun) error
}

Job is an interface for submitted cron jobs.

func Chain

func Chain(j IntoJob, wrappers ...JobWrapper) Job

Chain `Chain(j, w1, w2, w3)` -> `w3(w2(w1(j)))`

func DelayIfStillRunning

func DelayIfStillRunning(j IntoJob) Job

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 J

func J(v IntoJob) Job

J is a helper to turn a IntoJob into a Job. It panics with ErrUnsupportedJobType for other types. A Job, any of these functions, or a value having a "Run" method with one of these signatures (eg: "func (MyJob) Run(context.Context) error") can be turned into a Job:

func()
func() error
func(context.Context)
func(context.Context) error
func(cron.EntryID)
func(cron.EntryID) error
func(cron.Entry)
func(cron.Entry) error
func(*cron.Cron)
func(*cron.Cron) error
func(cron.JobRun)
func(cron.JobRun) error
func(context.Context, cron.EntryID)
func(context.Context, cron.EntryID) error
func(context.Context, cron.Entry)
func(context.Context, cron.Entry) error
func(context.Context, *cron.Cron)
func(context.Context, *cron.Cron) error
func(context.Context, cron.JobRun)
func(context.Context, cron.JobRun) error
func(*cron.Cron, cron.EntryID)
func(*cron.Cron, cron.EntryID) error
func(*cron.Cron, cron.Entry)
func(*cron.Cron, cron.Entry) error
func(*cron.Cron, cron.JobRun)
func(*cron.Cron, cron.JobRun) error
func(context.Context, *cron.Cron, cron.EntryID)
func(context.Context, *cron.Cron, cron.EntryID) error
func(context.Context, *cron.Cron, cron.Entry)
func(context.Context, *cron.Cron, cron.Entry) error
func(context.Context, *cron.Cron, cron.JobRun)
func(context.Context, *cron.Cron, cron.JobRun) error

func N

func N(n int, j IntoJob) Job

N runs a job "n" times

func Once

func Once(job IntoJob) Job

Once runs a job only one time, the entry is removed when the job starts.

func SkipIfStillRunning

func SkipIfStillRunning(j IntoJob) Job

SkipIfStillRunning skips an invocation of the Job if a previous invocation is still running.

func ThresholdClb

func ThresholdClb(threshold time.Duration, j IntoJob, clb ThresholdCallback) Job

ThresholdClb execute a callback if the job runs longer than the specified threshold.

func ThresholdClbAsync

func ThresholdClbAsync(threshold time.Duration, j IntoJob, clb ThresholdCallbackAsync) Job

ThresholdClbAsync calls the callback (asynchronously) if the job is still running after the threshold

func WithDeadline

func WithDeadline(deadline time.Time, job IntoJob) Job

func WithJitter

func WithJitter(duration time.Duration, job IntoJob) Job

WithJitter add some random delay before running the job

func WithRetry

func WithRetry(maxRetry int, job IntoJob) Job

WithRetry runs a job with retries up to maxRetry times

func WithRetryPolicy added in v1.0.0

func WithRetryPolicy(policy RetryPolicy, job IntoJob) Job

WithRetryPolicy runs a job with retries, as configured by the policy (see RetryPolicy):

cron.WithRetryPolicy(cron.RetryPolicy{MaxRetries: 5, MaxDelay: time.Minute, Jitter: 0.2}, job)

func WithTimeout

func WithTimeout(d time.Duration, job IntoJob) Job

WithTimeout cancels the context of the job after the given duration: `_, _ = cron.AddJob("* * * * * *", cron.WithTimeout(time.Second, func(ctx context.Context) { ... }))`

type JobEvent

type JobEvent struct {
	Typ       JobEventType
	CreatedAt time.Time
}

type JobEventType

type JobEventType int
const (
	JobStart JobEventType = iota + 1
	JobCompleted
	JobErr
	JobPanic
)

func (JobEventType) String

func (e JobEventType) String() string

type JobRun

type JobRun struct {
	RunID       RunID      // Unique identifier for this job run
	Entry       Entry      // Job definition being executed
	CreatedAt   time.Time  // When the run was created
	ScheduledAt time.Time  // Activation time the run is for (the time Trigger was called for a triggered run)
	Triggered   bool       // The run was started by Trigger (or RunNow), not by the schedule
	StartedAt   *time.Time // When execution began (nil if not started)
	CompletedAt *time.Time // When execution finished (nil if not completed)
	Events      []JobEvent // Timeline of events during execution
	Error       error      // Final error state if any
	Panic       bool       // Whether job panicked during execution
	Logs        string     // Captured log output
	// contains filtered or unexported fields
}

JobRun represents a single execution of a scheduled job.

func (JobRun) Logger

func (j JobRun) Logger() Logger

Logger returns the structured logger for this job run

type JobRunLoggerFactory

type JobRunLoggerFactory interface {
	// New creates a new slog.Logger instance that writes to the given io.Writer.
	New(w io.Writer) Logger
}

JobRunLoggerFactory is an interface for creating loggers for individual job runs. Implementations should create a new logger that writes to the provided io.Writer.

func DefaultJobRunLoggerFactory

func DefaultJobRunLoggerFactory() JobRunLoggerFactory

DefaultJobRunLoggerFactory returns a default implementation of JobRunLoggerFactory. The default implementation creates a text-based logger with debug level logging that writes to the provided io.Writer.

type JobWrapper

type JobWrapper func(IntoJob) Job

func DeadlineWrapper

func DeadlineWrapper(deadline time.Time) JobWrapper

func JitterWrapper

func JitterWrapper(duration time.Duration) JobWrapper

JitterWrapper add some random delay before running the job

func NWrapper

func NWrapper(n int) JobWrapper

NWrapper creates a JobWrapper that runs a job "n" times, then removes the entry. It panics if n <= 0.

func RetryPolicyWrapper added in v1.0.0

func RetryPolicyWrapper(policy RetryPolicy) JobWrapper

RetryPolicyWrapper creates a JobWrapper retrying the job when it returns an error, as configured by the policy. It stops retrying when the context is cancelled, and returns the error of the last attempt. The retries are logged with the logger of the job run.

func ThresholdClbAsyncWrapper

func ThresholdClbAsyncWrapper(threshold time.Duration, clb ThresholdCallbackAsync) JobWrapper

ThresholdClbAsyncWrapper wraps a job and starts a timer for the given threshold. If the job runs longer than the threshold, the callback is triggered. The callback is invoked asynchronously and does not block job execution.

func ThresholdClbWrapper

func ThresholdClbWrapper(threshold time.Duration, clb ThresholdCallback) JobWrapper

func TimeoutWrapper

func TimeoutWrapper(duration time.Duration) JobWrapper

TimeoutWrapper automatically cancel the job context after a given duration

func WithRetryWrapper

func WithRetryWrapper(maxRetry int) JobWrapper

WithRetryWrapper creates a JobWrapper that retries a job up to maxRetry times. It waits (attempt * 1s) between attempts, stops retrying when the context is cancelled, and returns the error of the last attempt.

type Logger

type Logger interface {
	// Debug logs a debug message with optional key-value pairs
	Debug(msg string, keysAndValues ...any)
	// Info logs an informational message with optional key-value pairs
	Info(msg string, keysAndValues ...any)
	// Warn logs a warning message with optional key-value pairs
	Warn(msg string, keysAndValues ...any)
	// Error logs an error message with optional key-value pairs
	Error(msg string, keysAndValues ...any)
}

Logger is the interface used in this package for logging, so that any backend can be plugged in.

var DefaultLogger Logger = slog.Default()

DefaultLogger is used by Cron if none is specified.

var DiscardLogger Logger = slog.New(slog.NewTextHandler(io.Discard, nil))

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

type Metrics added in v1.0.0

type Metrics interface {
	// JobStarted is called when a job run starts. delay is how late it started compared
	// to its scheduled time (JobRun.ScheduledAt).
	JobStarted(run JobRun, delay time.Duration)
	// JobCompleted is called when a job run completes. JobRun.Error and JobRun.Panic tell how it ended.
	JobCompleted(run JobRun, duration time.Duration)
	// JobSkipped is called when an activation of an entry does not run, see SkipReason.
	JobSkipped(entry Entry, scheduledAt time.Time, reason SkipReason)
}

Metrics receives measurements of the job runs, eg: to export them to Prometheus (counters of started / failed / skipped runs, histograms of durations and delays).

The methods are called synchronously by the cron, from the goroutine of the job run (or the scheduler loop for JobSkipped): they must be fast and safe for concurrent use. A panic in a method is recovered and logged.

Implementations should embed BaseMetrics, so that methods added to this interface in the future do not break them.

type MisfirePolicy added in v1.0.0

type MisfirePolicy int

MisfirePolicy tells what to do with the activations of an entry that were missed: the cron was not running at that time, or could not run the job on time (eg: the machine was sleeping).

const (
	// MisfireDefault uses the policy of the cron (Builder.WithMisfirePolicy) for an entry.
	// As the policy of the cron, the activations missed while the cron is running run once
	// (like MisfireRunOnce), and those missed while it is not running are skipped.
	MisfireDefault MisfirePolicy = iota
	// MisfireSkip skips the activations missed by more than the misfire threshold
	// (Builder.WithMisfireThreshold), the entry runs at its next activation.
	MisfireSkip
	// MisfireRunOnce runs the job once for all the missed activations, as soon as possible.
	MisfireRunOnce
	// MisfireRunAll runs the job once for each missed activation, as soon as possible
	// (JobRun.ScheduledAt is the activation each run is for). With a frequent schedule, this
	// can be a lot of runs: wrap the job with DelayIfStillRunning to run them one at a time.
	MisfireRunAll
)

func (MisfirePolicy) String added in v1.0.0

func (p MisfirePolicy) String() string

type ParseOption

type ParseOption int

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         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 such as @monthly, @weekly, etc.
)

type Parser

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

A custom Parser that can be configured.

func NewParser

func NewParser(options ParseOption) Parser

NewParser creates a Parser 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 := NewParser(Minute | Hour | Dom | Month | Dow)
sched, err := specParser.Parse("0 0 15 */3 *")

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

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

func (Parser) Parse

func (p Parser) 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 NewParser.

type RetryPolicy added in v1.0.0

type RetryPolicy struct {
	// MaxRetries is the maximum number of retries after the first attempt.
	MaxRetries int
	// InitialDelay is the delay before the first retry (default: one second).
	InitialDelay time.Duration
	// MaxDelay caps the delay between two attempts (0 = no cap).
	MaxDelay time.Duration
	// Multiplier is the growth of the delay between two retries (default: 2, 1 = constant delay).
	// Values below 1 are treated as 1.
	Multiplier float64
	// Jitter randomizes each delay by ±Jitter, from 0 (default, no randomization) to 1:
	// 0.2 is a delay between 80% and 120% of the computed one. Spreads the retries of many jobs.
	Jitter float64
	// RetryIf tells if an error should be retried (nil = all errors are retried).
	RetryIf func(error) bool
}

RetryPolicy configures the retries of WithRetryPolicy / RetryPolicyWrapper.

The delay before the retry n (starting at 0) is InitialDelay * Multiplier^n, capped at MaxDelay, then randomized by ±Jitter: with the defaults, the retries wait 1s, 2s, 4s, 8s...

func (RetryPolicy) Delay added in v1.0.0

func (p RetryPolicy) Delay(n int) time.Duration

Delay returns the delay before the retry n (starting at 0), see RetryPolicy.

type RunID

type RunID ID

RunID represents a unique identifier for a job run.

type Schedule

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

The 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 ScheduleParser

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

ScheduleParser is an interface for schedule spec parsers that return a Schedule

type SkipReason added in v1.0.0

type SkipReason int

SkipReason tells why an activation of an entry did not run

const (
	// SkipMisfire the activation was missed by more than the misfire threshold, with the MisfireSkip policy
	SkipMisfire SkipReason = iota + 1
	// SkipStillRunning a previous run of the entry was still running, with the NoOverlap option
	SkipStillRunning
)

func (SkipReason) String added in v1.0.0

func (r SkipReason) String() string

type SpecSchedule

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

	// Override location for this schedule.
	Location *time.Location
	// contains filtered or unexported fields
}

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(t 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.

Daylight saving time transitions are handled as Vixie cron does (see "Daylight saving time" in the package documentation):

  • a time that does not exist (the clock jumps forward) activates at the end of the jump, unless the schedule is an interval (its second, minute or hour field starts with '*'): the time is then skipped;
  • a time that occurs twice (the clock goes back) activates only the first time, unless the schedule is an interval: it then activates both times.

func (*SpecSchedule) Prev added in v1.0.0

func (s *SpecSchedule) Prev(t time.Time) time.Time

Prev returns the last time this schedule was activated, before the given time (the activation preceding t, as computed by Next). If no time can be found within five years, it returns the zero time.

type ThresholdCallback

type ThresholdCallback func(ctx context.Context, c *Cron, r JobRun, threshold, dur time.Duration, err error)

type ThresholdCallbackAsync

type ThresholdCallbackAsync func(ctx context.Context, c *Cron, r JobRun, threshold time.Duration)

Directories

Path Synopsis
internal
mtx
Package mtx provides thread-safe wrappers for values and maps using read-write mutexes.
Package mtx provides thread-safe wrappers for values and maps using read-write mutexes.

Jump to

Keyboard shortcuts

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