Documentation
¶
Overview ¶
Package cron parses cron expressions and computes their fire times.
It is a parser and next-run calculator that import only the standard library, read no clock (every call takes the reference instant as an argument) and evaluate every schedule in an explicit time zone.
Syntax ¶
A standard five-field expression is "minute hour day-of-month month day-of-week". Each field is a comma-separated list of items; an item is "*", a value "5", or a range "1-10", optionally followed by a step "/n" ("*/15", "1-10/2", "5/20" meaning 5-max/20). Months accept JAN-DEC and weekdays SUN-SAT, case-insensitive. Sunday is 0 or 7.
Macros: @yearly and @annually ("0 0 1 1 *"), @monthly ("0 0 1 * *"), @weekly ("0 0 * * 0"), @daily and @midnight ("0 0 * * *"), @hourly ("0 * * * *"), and "@every <duration>" for a fixed interval.
Day matching (the Vixie rule) ¶
When both day-of-month and day-of-week are restricted (neither field starts with "*"), a day matches if EITHER field matches: "0 0 1 * MON" fires on the 1st of every month and on every Monday. When either field starts with "*" (including "*/2"), both must match, as in Vixie cron.
Daylight saving time ¶
Wall-clock schedules are evaluated in the zone passed to Next. Two rules decide what happens when the wall clock jumps, chosen by the hour field:
- Fixed-time schedules (the hour field does not match all 24 hours, e.g. "30 2 * * *"): a wall time that does not exist on that day (the spring-forward gap) fires ONCE at the first valid instant after the gap; a wall time that occurs twice (the fall-back overlap) fires ONCE, on its first occurrence. A daily job therefore runs exactly once per day.
- Periodic schedules (the hour field matches every hour, e.g. "0 * * * *" or "* * * * *"): they follow real time. A wall time inside the gap is not a real instant and does not fire; a wall time inside the overlap fires on both occurrences. No real matching instant is skipped or fired twice.
"@every" intervals ignore the wall clock entirely, so DST never moves them.
Builder writes expressions from named frequencies (Daily().At("9:00").Weekdays()); see builder.go.
Index ¶
- Variables
- func LoadZone(name string) (*time.Location, error)
- type Builder
- func Daily() Builder
- func DailyAt(hhmm string) Builder
- func EveryHours(n int) Builder
- func EveryMinute() Builder
- func EveryMinutes(n int) Builder
- func EverySeconds(n int) Builder
- func Hourly() Builder
- func HourlyAt(minute int) Builder
- func Monthly() Builder
- func MonthlyOn(day int, hhmm string) Builder
- func Quarterly() Builder
- func QuarterlyOn(day int, hhmm string) Builder
- func TwiceDaily(first, second int) Builder
- func TwiceDailyAt(first, second, minute int) Builder
- func TwiceMonthly(first, second int, hhmm string) Builder
- func Weekly() Builder
- func WeeklyOn(day time.Weekday, hhmm string) Builder
- func Yearly() Builder
- func YearlyOn(month time.Month, day int, hhmm string) Builder
- type Calendar
- type ParseError
- type Parser
- type Schedule
Constants ¶
This section is empty.
Variables ¶
var ErrBuilder = errors.New("cron: invalid builder")
ErrBuilder is wrapped by every error a Builder returns, so a caller can tell a bad frequency call from a parse error of a hand-written expression.
var ErrCalendar = errors.New("cron: invalid calendar")
ErrCalendar is wrapped by every error Calendar returns, so a caller can tell a bad structured spec from a parse error of a hand-written expression.
var ErrZone = errors.New("cron: invalid time zone")
ErrZone is wrapped by every error LoadZone returns.
Functions ¶
func LoadZone ¶
LoadZone loads an IANA zone by name for a schedule, so an unknown or implicit zone fails when the app boots, not as a schedule that silently fires at the wrong hour. It refuses "" and "Local" (both mean the host's zone, which differs from machine to machine; time.LoadLocation turns "" into UTC and "Local" into the host zone without a word) and any name time.LoadLocation cannot find. The error wraps ErrZone and names the zone.
A container image without a zoneinfo database finds no zone but UTC; import the cron/tzdata package (or time/tzdata) to embed one.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder writes a cron expression from named frequencies (Daily, EveryMinutes(5), Weekdays, At("13:00")). It emits the same expression a person would write, never a new format, so every driver keeps parsing one syntax and the result can be stored, logged and read back as text. Most frequencies emit five plain fields, which every driver takes (Hatchet refuses macros); EverySeconds emits "@every <n>s", which the memory and SQL drivers take and Hatchet refuses.
A Builder is an immutable value: each method returns a new one, so a base frequency can be shared and refined. Invalid input does not panic and does not produce a wrong expression: the first error is kept and returned by Expr, wrapping ErrBuilder. The zero Builder is invalid; start from one of the frequency functions.
The frequencies and their expressions:
EverySeconds(n) @every <n>s (n divides 60)
EveryMinute() * * * * *
EveryMinutes(5) */5 * * * * (n divides 60)
Hourly() 0 * * * *
HourlyAt(17) 17 * * * *
EveryHours(2) 0 */2 * * * (n is 2, 3, 4, 6, 8 or 12)
Daily() 0 0 * * *
DailyAt("13:00") 0 13 * * *
TwiceDaily(1, 13) 0 1,13 * * *
TwiceDailyAt(1, 13, 15) 15 1,13 * * *
Weekly() 0 0 * * 0
WeeklyOn(1, "8:00") 0 8 * * 1
Monthly() 0 0 1 * *
MonthlyOn(4, "15:00") 0 15 4 * *
TwiceMonthly(1, 16, "13:00") 0 13 1,16 * *
Quarterly() 0 0 1 1,4,7,10 *
QuarterlyOn(4, "14:00") 0 14 4 1,4,7,10 *
Yearly() 0 0 1 1 *
YearlyOn(6, 1, "17:00") 0 17 1 6 *
and the constraints:
.At("13:00") sets minute and hour
.Weekdays() day of week 1-5
.Weekends() day of week 0,6
.Days(time.Monday, ...) day of week list
The last day of the month has no five-field form and is not offered; time windows and conditions belong to a schedule, not to the expression.
func EveryHours ¶
EveryHours fires at minute 0 every n hours from midnight: "0 */n * * *". n must divide 24 so the step is even across midnight.
func EveryMinute ¶
func EveryMinute() Builder
EveryMinute fires at the start of every minute: "* * * * *".
func EveryMinutes ¶
EveryMinutes fires every n minutes from minute 0 of each hour: "*/n * * * *". n must divide 60, because "*/7" fires at :56 and again at :00, four minutes later; for an uneven step write the expression by hand. EveryMinutes(1) is EveryMinute.
func EverySeconds ¶
EverySeconds fires every n seconds as "@every <n>s". n must divide 60 so the ticks fall at the same seconds of every minute; for another interval write "@every 90s" by hand. Constraints (At, Days) are refused: an interval ignores the wall clock.
func MonthlyOn ¶
MonthlyOn fires on day (1-31) of every month at hhmm. Months without that day are skipped, as in cron: MonthlyOn(31, ...) fires seven times a year.
func Quarterly ¶
func Quarterly() Builder
Quarterly fires at midnight on the 1st of January, April, July and October: "0 0 1 1,4,7,10 *".
func QuarterlyOn ¶
QuarterlyOn fires on day (1-31) of the first month of each quarter at hhmm.
func TwiceDaily ¶
TwiceDaily fires at minute 0 of two hours (0-23) every day.
func TwiceDailyAt ¶
TwiceDailyAt fires at the given minute of two hours every day.
func TwiceMonthly ¶
TwiceMonthly fires on two days of every month at hhmm.
func Weekly ¶
func Weekly() Builder
Weekly fires at midnight on Sunday: "0 0 * * 0". Days changes the day.
func YearlyOn ¶
YearlyOn fires once a year on month and day at hhmm. A day the month never has (30 February) is refused rather than producing a schedule that never fires; 29 February is accepted and fires in leap years only.
func (Builder) At ¶
At sets the time of day, hhmm as "13:00" or "9:05" (24-hour clock). It applies to frequencies that fire once on a day (Daily, Weekly, Monthly, Quarterly, Yearly and their On forms); on an hourly, minute or second frequency it is refused, because replacing the minute and hour would silently drop the repetition: use DailyAt, HourlyAt or TwiceDailyAt.
func (Builder) Days ¶
Days limits the frequency to the given weekdays. On Weekly it picks the day the week fires on. It is refused on a frequency that also fixes the day of the month (Monthly, Quarterly, Yearly and their On forms): cron fires when EITHER day field matches there (the Vixie rule), so Monthly().Days(Monday) would fire on the 1st and on every Monday, not on Mondays that are the 1st.
func (Builder) Expr ¶
Expr returns the expression, checked by Parse, or the first error a call made, wrapping ErrBuilder.
func (Builder) MustExpr ¶
MustExpr is Expr for a frequency written as constants in the program (Workflow.Cron, a package-level schedule), where an error is a bug: it panics with Expr's error. Use Expr for input that comes from users or configuration.
func (Builder) Schedule ¶
Schedule parses the expression, for computing fire times (Next, Between) without a driver.
type Calendar ¶
type Calendar struct {
// Minute lists minutes 0-59; empty means minute 0.
Minute []int
// Hour lists hours 0-23; empty means every hour.
Hour []int
// DayOfMonth lists days 1-31; empty means every day.
DayOfMonth []int
// Month lists months; empty means every month.
Month []time.Month
// DayOfWeek lists weekdays; empty means every day of the week.
DayOfWeek []time.Weekday
}
Calendar is a structured calendar spec: the fire times as lists of field values instead of a cron string ("hour 9, minutes 0 and 30, Monday to Friday"). An empty list means every value of that field, except Minute, where empty means minute 0, so Calendar{Hour: []int{9}} fires once at 09:00 rather than sixty times. It compiles to the five-field expression a person would write (Expr), never a new format, so every driver takes it, and a stored schedule stays plain text.
Day matching is AND, the way people read a calendar: DayOfMonth and DayOfWeek together would need "the 13th AND a Friday", which a cron expression cannot say (cron ORs two restricted day fields), so setting both is refused rather than compiled into an expression that fires on every 13th and every Friday.
type ParseError ¶
type ParseError struct {
Expr string // the full expression as given
Field string // "minute", "hour", "day-of-month", "month", "day-of-week", "macro" or "expression"
Value string // the offending text within the field
Reason string // what is wrong with it
}
ParseError reports an invalid expression and names the offending field, so a typo fails loudly at registration instead of silently at run time.
type Parser ¶
Parser turns an expression into a Schedule. Parse is the default every driver uses, which is what makes one expression mean the same on every driver. A driver that accepts a custom Parser (memory.WithCronParser) lets an app bring another dialect (the extended "L", "W" and "#" fields, a seconds field, "H" hashing): the app gives up that promise for the expressions only its parser understands, since an engine with its own cron dialect still refuses them. A Parser must return a Schedule that keeps the interface's contract (Next never returns a time at or before after; nil loc means UTC) and must be safe for concurrent use.
type Schedule ¶
type Schedule interface {
// Next returns the first fire time strictly after `after`, expressed in
// loc. A nil loc means UTC, never the host zone, so the same schedule
// behaves identically on every machine. It returns the zero time when no
// fire time exists within searchYears of `after` (for example "0 0 30 2
// *", February 30th); callers must check IsZero.
Next(after time.Time, loc *time.Location) time.Time
// Between returns the fire times t with from < t <= to, ascending, at
// most limit of them (limit <= 0 returns nil). The half-open range lets
// a caller chain windows (last checked, now] without double-counting a
// fire; limit bounds memory when a misfire window is unexpectedly long.
Between(from, to time.Time, loc *time.Location, limit int) []time.Time
// String returns the expression as parsed (trimmed), so a schedule can
// be stored and later re-parsed into an equivalent schedule.
String() string
}
Schedule is a parsed schedule. Implementations are immutable and safe for concurrent use.
func Parse ¶
Parse parses a five-field cron expression, a macro, or "@every <duration>". Every error is a *ParseError naming the bad field. It is the default Parser.
func ParseSeconds ¶
ParseSeconds is a Parser for the six-field dialect with a seconds field first: "second minute hour day-of-month month day-of-week" ("*/10 * * * * *" fires every ten seconds, "30 0 9 * * MON-FRI" at 09:00:30 on weekdays). The other five fields, the macros and "@every" mean exactly what they mean to Parse; a macro fires at second 0.
It is opt-in and never auto-detected, because six fields are ambiguous: some dialects put seconds first, while others put a year last. Pass it where a driver takes a Parser (memory.WithCronParser and the SQL driver's WithCronParser); an engine with its own five-field dialect (Hatchet) still refuses the expressions, so a schedule written for it is no longer portable to every driver.
DST follows the minute the seconds belong to: a fixed-time minute that falls in a spring-forward gap fires at the first instant after the gap plus its seconds, and the periodic rule (the hour field matches every hour) fires both occurrences of an overlapping minute.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package tzdata embeds the IANA time zone database in the binary, for apps that run schedules in a container image without one (scratch, distroless and many slim images ship no /usr/share/zoneinfo).
|
Package tzdata embeds the IANA time zone database in the binary, for apps that run schedules in a container image without one (scratch, distroless and many slim images ship no /usr/share/zoneinfo). |