Documentation
¶
Overview ¶
Package cron implements a cron spec parser and job runner.
The library is organized into two primary components:
- Parser: parses cron specification strings into a Schedule. Custom parsers can be created to support alternative formats.
- Scheduler: the Cron instance keeps track of jobs and executes them according to their Schedule.
This separation allows parsing schedules independently, reusing a single schedule for multiple jobs, or providing custom Schedule implementations directly to the scheduler.
Usage ¶
Callers may register funcs to be invoked on a given schedule. Cron will run them in their own goroutines.
c := cron.New()
parser, _ := cron.NewDefaultParser(cron.StandardOptions)
sched, _ := parser.Parse("30 * * * *")
c.Schedule(sched, func() { fmt.Println("Every hour on the half hour") })
sched, _ = parser.Parse("30 3-6,20-23 * * *")
c.Schedule(sched, func() { fmt.Println(".. in the range 3-6am, 8-11pm") })
sched, _ = parser.Parse("CRON_TZ=Asia/Tokyo 30 04 * * *")
c.Schedule(sched, func() { fmt.Println("Runs at 04:30 Tokyo time every day") })
sched, _ = parser.Parse("@hourly")
c.Schedule(sched, func() { fmt.Println("Every hour, starting an hour from now") })
sched, _ = parser.Parse("@every 1h30m")
c.Schedule(sched, func() { fmt.Println("Every hour thirty, starting an hour thirty from now") })
c.Start()
..
// Funcs are invoked in their own goroutine, asynchronously.
...
// Funcs may also be added to a running Cron
sched, _ = parser.Parse("@daily")
c.Schedule(sched, func() { fmt.Println("Every day") })
..
// Inspect the cron job entries' next and previous run times.
inspect(c.Entries())
..
c.Stop() // Stop the scheduler (does not stop any jobs already running).
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 | * / , - ? L W Month | Yes | 1-12 or JAN-DEC | * / , - Day of week | Yes | 0-6 or SUN-SAT | * / , - ? L #
Month and Day-of-week field values are case insensitive. "SUN", "Sun", and "sun" are equally accepted.
The specific interpretation of the format is mainly based on the Cron Wikipedia page: https://en.wikipedia.org/wiki/Cron
Alternative Formats ¶
Alternative Cron expression formats support other fields like seconds. This can be implemented by creating a custom Parser to generate a Schedule:
parser, _ := cron.NewDefaultParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
sched, _ := parser.Parse("* * * * * *")
To emulate Quartz, the most popular alternative Cron schedule format, the seconds field can be required: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html
parser, _ := cron.NewDefaultParser( cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
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.
Last ( L )
L char can be used in day-of-month field meaning the last day of the month. It can be used subtracting a number of days, for example L-1 would mean "One day before the last day of the month" (30th for months with 31 days). Cannot be used with steps (slash).
L char can be also used in day-of-week field. If alone, it's equivalent to 6 (Saturday). If used after a day-of-week value it indicates the last occurence of that dow in the month. For example, FRIL would mean the last friday of the month. Cannot be used with steps or ranges.
L char can be combined with W (LW) meaning the last weekday of the month. LW cannot be used with steps or ranges.
Nearest weekday ( W )
W char can be used in day-of-month field to specify the weekday (Monday-Friday) nearest the given day. For example, given 19W dom, if the 19th is Saturday the expression would activate on Friday 18th. If the 19th is a Sunday instead, the expression would activate on Monday 20th. The W char looks for weekdays within the month boundaries. Given a 1W dom with the 1st being a Saturday, the expression would activate on Monday 3rd. Cannot be used with steps or ranges.
Nth occurrence ( # )
Nth occurence char can be used in day-of-week field and allows to specify an occurence of a specific dow within the month. For example, SUN#2 means the second Sunday of the month. Cannot be used with steps or ranges.
Predefined schedules ¶
One of several pre-defined schedules may be used 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 ¶
Jobs may also be scheduled to execute at fixed intervals, starting at the time they are 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), multiple of one second.
For example, "@every 1h30m10s" would indicate a schedule that activates after 1 hour, 30 minutes, 10 seconds, and then every interval after that.
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.
Clock and time zones ¶
Cron use a Clock interface when interacting with time. A custom clock can be set using WithClock option. Two manual clocks are provided for testing purposes, both skipping the wait between scheduled activations: NewTimerSkippingInstantExecutionClock runs each job to completion in no virtual time at all, while NewTimerSkippingRealExecutionClock lets jobs execute in real time with the clock flowing along with them, which is what testing overlapping executions (see WithQueueIfRunning, WithSkipIfRunning) requires.
The clock is also responsible for defining the timezone to be used when applying the cron schedule. The default clock can be created with a different timezone using NewDefaultClock. By default, all interpretation and scheduling is done in the machine's local time zone (time.Local).
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
parser, _ := cron.NewDefaultParser(cron.StandardOptions)
sched, _ := parser.Parse("0 6 * * ?")
cron.New().Schedule(sched, ...)
# Runs at 6am in America/New_York
nyc, _ := time.LoadLocation("America/New_York")
c := cron.New(cron.WithClock(cron.NewDefaultClock(nyc, cron.DefaultNopTimer)))
sched, _ = parser.Parse("0 6 * * ?")
c.Schedule(sched, ...)
# Runs at 6am in Asia/Tokyo
sched, _ = parser.Parse("CRON_TZ=Asia/Tokyo 0 6 * * ?")
cron.New().Schedule(sched, ...)
The prefix "TZ=(TIME ZONE)" is also supported for legacy compatibility.
A schedule's timezone can be modified programmatically using the DefaultSchedule.WithLocation method:
sched, _ = parser.Parse("0 6 * * ?")
nycSched := sched.WithLocation(nyc)
cron.New().Schedule(nycSched, ...)
Be aware that jobs scheduled during daylight-savings leap-ahead transitions will not be run!
Minimum interval ¶
DefaultSchedule.MinInterval returns the shortest time between two consecutive activations of a schedule, for instance to check that a job completes before it can be triggered again:
sched, _ = parser.Parse("0 9 * * 1,4")
sched.MinInterval() // 72h, from Monday to Thursday
Month lengths, leap years and weekdays are taken into account, as well as the clock changes of the schedule's location, assumed to keep following their current rules: in Paris, "30 2 * * *" runs twice an hour apart when clocks go back from 3:00 to 2:00, and "@daily" runs 23 hours apart when they go forward. A schedule without a time zone is assumed to run in time.Local. The result is computed on first use, which takes about a millisecond, and cached afterwards.
Overlapping executions ¶
A Cron runner may be configured to control how overlapping executions of the same job are handled. For example:
- Skip a job's execution if the previous run hasn't completed yet
- Delay (queue) a job's execution until the previous run has completed
Skip overlapping executions using the WithSkipIfRunning option:
cron.New(cron.WithSkipIfRunning())
Queue overlapping executions using the WithQueueIfRunning option:
cron.New(cron.WithQueueIfRunning())
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 use log/slog package for logging. The logger can be set through its option:
cron.New(cron.WithLogger(slog.Default()))
Implementation ¶
Cron entries are stored in a min heap based on 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 heap of entries by next activation time.
- it goes to sleep until the soonest job.
Index ¶
- Constants
- type Clock
- type Cron
- type DefaultClock
- type DefaultParser
- type DefaultSchedule
- type Entry
- type ID
- type Option
- type ParseOption
- type Schedule
- type TimerSkippingInstantExecutionClock
- func (c *TimerSkippingInstantExecutionClock) AdvanceBy(duration time.Duration)
- func (c *TimerSkippingInstantExecutionClock) AdvanceTo(target time.Time)
- func (c *TimerSkippingInstantExecutionClock) NopTimer() (<-chan struct{}, func())
- func (c *TimerSkippingInstantExecutionClock) Now() time.Time
- func (c *TimerSkippingInstantExecutionClock) Register(cron *Cron) []Option
- func (c *TimerSkippingInstantExecutionClock) Timer(t time.Time) (<-chan struct{}, func())
- type TimerSkippingRealExecutionClock
- func (c *TimerSkippingRealExecutionClock) AdvanceBy(duration time.Duration)
- func (c *TimerSkippingRealExecutionClock) AdvanceTo(target time.Time)
- func (c *TimerSkippingRealExecutionClock) NopTimer() (<-chan struct{}, func())
- func (c *TimerSkippingRealExecutionClock) Now() time.Time
- func (c *TimerSkippingRealExecutionClock) Register(cron *Cron) []Option
- func (c *TimerSkippingRealExecutionClock) Timer(t time.Time) (<-chan struct{}, func())
- func (c *TimerSkippingRealExecutionClock) WaitForIdle()
Constants ¶
const DefaultNopTimer = 100_000 * time.Hour
const StandardOptions = Minute | Hour | Dom | Month | Dow | Descriptor
StandardOptions represents the default options for parsing standard cron strings. It includes 5 fields (Minute, Hour, Dom, Month, Dow) and the Descriptor option.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Clock ¶ added in v0.6.0
type Clock interface {
Register(*Cron) []Option
Now() time.Time
Timer(time.Time) (timer <-chan struct{}, stop func())
NopTimer() (timer <-chan struct{}, stop func())
}
The cron scheduler implements the following cycle:
- next job time evaluation
- timer setup: clock.NopTimer() when there are no jobs registered, clock.Timer() with the next activation time otherwise
- wakes up when timer fires or other actions are triggered (e.g. insertion, removal): handles event and move to next cycle iteration
Register() can be used for setting additional clock related options. Now() is expected to return the current time in line with the implemented clock behaviour. Current time must have the desired timezone set.
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.
type DefaultClock ¶ added in v0.7.0
type DefaultClock struct {
// contains filtered or unexported fields
}
func NewDefaultClock ¶ added in v0.6.0
func NewDefaultClock(location *time.Location, nop time.Duration) *DefaultClock
func (*DefaultClock) NopTimer ¶ added in v0.7.0
func (c *DefaultClock) NopTimer() (<-chan struct{}, func())
func (*DefaultClock) Now ¶ added in v0.7.0
func (c *DefaultClock) Now() time.Time
func (*DefaultClock) Register ¶ added in v0.7.0
func (c *DefaultClock) Register(cron *Cron) []Option
func (*DefaultClock) Timer ¶ added in v0.7.0
func (c *DefaultClock) Timer(t time.Time) (<-chan struct{}, func())
type DefaultParser ¶ added in v0.7.0
type DefaultParser struct {
// contains filtered or unexported fields
}
A default DefaultParser that can be configured.
func NewDefaultParser ¶ added in v0.7.0
func NewDefaultParser(options ParseOption) (*DefaultParser, error)
NewDefaultParser creates a DefaultParser 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, _ := NewDefaultParser(Minute | Hour | Dom | Month | Dow)
sched, err := specParser.Parse("0 0 15 */3 *")
// Same as above, just excludes time fields
specParser, _ := NewDefaultParser(Dom | Month | Dow)
sched, err := specParser.Parse("15 */3 *")
// Same as above, just makes Dow optional
specParser, _ := NewDefaultParser(Dom | Month | DowOptional)
sched, err := specParser.Parse("15 */3")
func (*DefaultParser) Parse ¶ added in v0.7.0
func (p *DefaultParser) Parse(spec string) (*DefaultSchedule, 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 NewDefaultParser.
type DefaultSchedule ¶ added in v0.7.0
type DefaultSchedule struct {
// contains filtered or unexported fields
}
Specifies a duty cycle (to the second granularity), based on a traditional crontab specification.
func (*DefaultSchedule) MinInterval ¶ added in v0.8.0
func (s *DefaultSchedule) MinInterval() time.Duration
MinInterval returns the shortest time that can separate two consecutive activations of the schedule, or zero if the schedule never activates.
All fields are taken into account, as well as the clock changes of the schedule's location: activations on either side of a change can be closer than usual, and those falling in an hour that is repeated occur twice. The changes of the coming years are taken from the time zone database, and assumed to recur in later years starting on the same day of the week and leap alike, as they do unless the rules change. A schedule without a location is assumed to run in time.Local.
The result is computed on first call, which takes about a millisecond, and cached afterwards.
func (*DefaultSchedule) Next ¶ added in v0.7.0
func (s *DefaultSchedule) 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.
Local times repeated by a clock change of the schedule's location activate it twice, and those skipped by one do not activate it.
func (*DefaultSchedule) WithLocation ¶ added in v0.7.0
func (s *DefaultSchedule) WithLocation(l *time.Location) *DefaultSchedule
WithLocation returns a copy of the schedule with the given location. If the location is nil, it returns the original schedule.
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 ID
// 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
// contains filtered or unexported fields
}
Entry consists of a schedule and the func to execute on that schedule.
type Option ¶
type Option func(*Cron)
Option represents a modification to the default behavior of a Cron.
func WithOnCycleCompleted ¶ added in v0.6.0
func WithOnCycleCompleted(f func()) Option
WithOnCycleCompleted registers a callback that will be executed every time all jobs executions that have been started in the same instant have completed.
func WithQueueIfRunning ¶ added in v0.8.0
func WithQueueIfRunning() Option
WithQueueIfRunning defers an activation that comes due while the previous run of the same job is still in progress, running it once that one completes.
The guard is per job, so distinct jobs never hold each other up. It is mutually exclusive with WithSkipIfRunning: giving both leaves the last one in effect. With neither, successive runs of the same job may overlap.
func WithSkipIfRunning ¶ added in v0.8.0
func WithSkipIfRunning() Option
WithSkipIfRunning skips an activation that comes due while the previous run of the same job is still in progress.
The guard is per job, so distinct jobs never hold each other up. It is mutually exclusive with WithQueueIfRunning: giving both leaves the last one in effect. With neither, successive runs of the same job may overlap.
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 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(time.Time) time.Time
}
Schedule describes a job's duty cycle.
type TimerSkippingInstantExecutionClock ¶ added in v0.7.0
type TimerSkippingInstantExecutionClock struct {
// contains filtered or unexported fields
}
func NewTimerSkippingInstantExecutionClock ¶ added in v0.6.0
func NewTimerSkippingInstantExecutionClock(start time.Time) *TimerSkippingInstantExecutionClock
func (*TimerSkippingInstantExecutionClock) AdvanceBy ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) AdvanceBy(duration time.Duration)
func (*TimerSkippingInstantExecutionClock) AdvanceTo ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) AdvanceTo(target time.Time)
func (*TimerSkippingInstantExecutionClock) NopTimer ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) NopTimer() (<-chan struct{}, func())
func (*TimerSkippingInstantExecutionClock) Now ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) Now() time.Time
func (*TimerSkippingInstantExecutionClock) Register ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) Register(cron *Cron) []Option
func (*TimerSkippingInstantExecutionClock) Timer ¶ added in v0.7.0
func (c *TimerSkippingInstantExecutionClock) Timer(t time.Time) (<-chan struct{}, func())
type TimerSkippingRealExecutionClock ¶ added in v0.8.0
type TimerSkippingRealExecutionClock struct {
// contains filtered or unexported fields
}
TimerSkippingRealExecutionClock is a manual clock that skips the wait between scheduled activations, like TimerSkippingInstantExecutionClock, but lets jobs execute in real time while the clock flows along with them.
While no job is running the clock is frozen and jumps straight to the next activation; while triggered jobs are executing it flows 1:1 with the wall clock, so that the jobs observe time passing and further activations fire as the flowing clock reaches them. AdvanceTo and AdvanceBy return as soon as the clock reaches the requested instant, without waiting for the jobs they started; WaitForIdle blocks until those jobs have completed and the clock is frozen again.
Every method is safe for concurrent use. AdvanceTo, AdvanceBy and WaitForIdle are serialized against each other: each runs to completion before the next one begins.
func NewTimerSkippingRealExecutionClock ¶ added in v0.8.0
func NewTimerSkippingRealExecutionClock(start time.Time) *TimerSkippingRealExecutionClock
func (*TimerSkippingRealExecutionClock) AdvanceBy ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) AdvanceBy(duration time.Duration)
AdvanceBy moves the virtual clock forward by duration, firing every activation scheduled within the interval. Jobs may still be running when it returns. There is no timeout: advancing needs a scheduler sleeping on a timer, and none is before Cron.Start or after Cron.Stop, so advancing then blocks forever.
func (*TimerSkippingRealExecutionClock) AdvanceTo ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) AdvanceTo(target time.Time)
AdvanceTo moves the virtual clock forward to target, firing every activation scheduled up to and including it. Jobs may still be running when it returns. There is no timeout: advancing needs a scheduler sleeping on a timer, and none is before Cron.Start or after Cron.Stop, so advancing then blocks forever.
func (*TimerSkippingRealExecutionClock) NopTimer ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) NopTimer() (<-chan struct{}, func())
func (*TimerSkippingRealExecutionClock) Now ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) Now() time.Time
func (*TimerSkippingRealExecutionClock) Register ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) Register(cron *Cron) []Option
func (*TimerSkippingRealExecutionClock) Timer ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) Timer(t time.Time) (<-chan struct{}, func())
func (*TimerSkippingRealExecutionClock) WaitForIdle ¶ added in v0.8.0
func (c *TimerSkippingRealExecutionClock) WaitForIdle()
WaitForIdle blocks until every job started by fired activations has completed and the clock is frozen again. There is no timeout: it blocks forever if a job never returns, or if jobs outlast the interval to the next activation, so that the flowing clock keeps starting new ones.