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 ¶
- Constants
- Variables
- func Activations(s Schedule, from time.Time) iter.Seq[time.Time]
- func Disabled(_ *Cron, entry *Entry)
- func HookDisable(hook *hookStruct)
- func HookSync(hook *hookStruct)
- func NextN(s Schedule, from time.Time, n int) []time.Time
- func NoOverlap(_ *Cron, entry *Entry)
- func RunOnStart(c *Cron, entry *Entry)
- type AtSchedule
- type BaseMetrics
- type Builder
- func (b *Builder) Build() *Cron
- func (b *Builder) KeepJobsRunningOnStop() *Builder
- func (b *Builder) Quiet() *Builder
- func (b *Builder) WithClock(clock clockwork.Clock) *Builder
- func (b *Builder) WithContext(ctx context.Context) *Builder
- func (b *Builder) WithIDFactory(idFactory IDFactory) *Builder
- func (b *Builder) WithJobRunLoggerFactory(jobRunLoggerFactory JobRunLoggerFactory) *Builder
- func (b *Builder) WithKeepCompletedRunsDur(keepCompletedRunsDur time.Duration) *Builder
- func (b *Builder) WithLocation(loc *time.Location) *Builder
- func (b *Builder) WithLogger(logger Logger) *Builder
- func (b *Builder) WithMaxCompletedRunsPerEntry(n int) *Builder
- func (b *Builder) WithMaxConcurrentJobs(n int) *Builder
- func (b *Builder) WithMaxLogSize(n int) *Builder
- func (b *Builder) WithMetrics(metrics Metrics) *Builder
- func (b *Builder) WithMisfirePolicy(policy MisfirePolicy) *Builder
- func (b *Builder) WithMisfireThreshold(threshold time.Duration) *Builder
- func (b *Builder) WithOptionalSeconds() *Builder
- func (b *Builder) WithParser(parser ScheduleParser) *Builder
- func (b *Builder) WithSeconds() *Builder
- func (b *Builder) WithTagConcurrencyLimit(tag string, n int) *Builder
- type ConstantDelaySchedule
- type Cron
- func (c *Cron) AddEntry(entry Entry, opts ...EntryOption) (EntryID, error)
- func (c *Cron) AddFunc(spec string, job FuncJob, opts ...EntryOption) (EntryID, error)
- func (c *Cron) AddJob(spec string, job IntoJob, opts ...EntryOption) (EntryID, error)
- func (c *Cron) AddJobAt(at time.Time, job IntoJob, opts ...EntryOption) (EntryID, error)
- func (c *Cron) AddJobStrict(spec string, job Job, opts ...EntryOption) (EntryID, error)
- func (c *Cron) CancelJobRun(entryID EntryID, runID RunID) error
- func (c *Cron) CleanupNow()
- func (c *Cron) CompletedJobRunsFor(entryID EntryID) ([]JobRun, error)
- func (c *Cron) CompletedJobs() []JobRun
- func (c *Cron) Disable(id EntryID) error
- func (c *Cron) DisableByTag(tag string) int
- func (c *Cron) DisableHook(id HookID) error
- func (c *Cron) Enable(id EntryID) error
- func (c *Cron) EnableByTag(tag string) int
- func (c *Cron) EnableHook(id HookID) error
- func (c *Cron) Entries() []Entry
- func (c *Cron) EntriesByTag(tag string) []Entry
- func (c *Cron) Entry(id EntryID) (Entry, error)
- func (c *Cron) GetCleanupTS() time.Time
- func (c *Cron) GetHook(id HookID) (Hook, error)
- func (c *Cron) GetHooks() []Hook
- func (c *Cron) GetJobRun(entryID EntryID, runID RunID) (JobRun, error)
- func (c *Cron) GetNextTime() time.Time
- func (c *Cron) IsRunning(id EntryID) bool
- func (c *Cron) JobRunCompletedCh() <-chan JobRun
- func (c *Cron) JobRunCreatedCh() <-chan JobRun
- func (c *Cron) Location() *time.Location
- func (c *Cron) NextActivations(id EntryID, n int) ([]time.Time, error)
- func (c *Cron) OnEntryEvt(entryID EntryID, evt JobEventType, clb HookFn, opts ...HookOption) HookID
- func (c *Cron) OnEntryJobCompleted(entryID EntryID, clb HookFn, opts ...HookOption) HookID
- func (c *Cron) OnEntryJobStart(entryID EntryID, clb HookFn, opts ...HookOption) HookID
- func (c *Cron) OnEvt(evt JobEventType, clb HookFn, opts ...HookOption) HookID
- func (c *Cron) OnJobCompleted(clb HookFn, opts ...HookOption) HookID
- func (c *Cron) OnJobStart(clb HookFn, opts ...HookOption) HookID
- func (c *Cron) RecentCompletedJobs(limit int) []JobRun
- func (c *Cron) Remove(id EntryID) error
- func (c *Cron) RemoveByTag(tag string) int
- func (c *Cron) RemoveHook(id HookID) error
- func (c *Cron) Run() (started bool)
- func (c *Cron) RunNow(id EntryID) error
- func (c *Cron) RunningJobs() []JobRun
- func (c *Cron) RunningJobsFor(entryID EntryID) ([]JobRun, error)
- func (c *Cron) Schedule(schedule Schedule, job Job, opts ...EntryOption) (EntryID, error)
- func (c *Cron) SetCleanupInterval(dur time.Duration)
- func (c *Cron) SetHookLabel(id HookID, label string) error
- func (c *Cron) SetLocation(newLoc *time.Location)
- func (c *Cron) SetTags(id EntryID, tags ...string) error
- func (c *Cron) Shutdown(ctx context.Context) error
- func (c *Cron) Start() (started bool)
- func (c *Cron) Stop() <-chan struct{}
- func (c *Cron) Trigger(id EntryID) (RunID, error)
- func (c *Cron) UpdateLabel(id EntryID, label string) error
- func (c *Cron) UpdateSchedule(id EntryID, schedule Schedule) error
- func (c *Cron) UpdateScheduleWithSpec(id EntryID, spec string) error
- func (c *Cron) Wait()
- type Entry
- type EntryID
- type EntryOption
- type FuncIDFactory
- type FuncJob
- type FuncJobRunLoggerFactory
- type Hook
- type HookFn
- type HookID
- type HookOption
- type ID
- type IDFactory
- type IntoJob
- type Job
- func Chain(j IntoJob, wrappers ...JobWrapper) Job
- func DelayIfStillRunning(j IntoJob) Job
- func J(v IntoJob) Job
- func N(n int, j IntoJob) Job
- func Once(job IntoJob) Job
- func SkipIfStillRunning(j IntoJob) Job
- func ThresholdClb(threshold time.Duration, j IntoJob, clb ThresholdCallback) Job
- func ThresholdClbAsync(threshold time.Duration, j IntoJob, clb ThresholdCallbackAsync) Job
- func WithDeadline(deadline time.Time, job IntoJob) Job
- func WithJitter(duration time.Duration, job IntoJob) Job
- func WithRetry(maxRetry int, job IntoJob) Job
- func WithRetryPolicy(policy RetryPolicy, job IntoJob) Job
- func WithTimeout(d time.Duration, job IntoJob) Job
- type JobEvent
- type JobEventType
- type JobRun
- type JobRunLoggerFactory
- type JobWrapper
- func DeadlineWrapper(deadline time.Time) JobWrapper
- func JitterWrapper(duration time.Duration) JobWrapper
- func NWrapper(n int) JobWrapper
- func RetryPolicyWrapper(policy RetryPolicy) JobWrapper
- func ThresholdClbAsyncWrapper(threshold time.Duration, clb ThresholdCallbackAsync) JobWrapper
- func ThresholdClbWrapper(threshold time.Duration, clb ThresholdCallback) JobWrapper
- func TimeoutWrapper(duration time.Duration) JobWrapper
- func WithRetryWrapper(maxRetry int) JobWrapper
- type Logger
- type Metrics
- type MisfirePolicy
- type ParseOption
- type Parser
- type RetryPolicy
- type RunID
- type Schedule
- type ScheduleParser
- type SkipReason
- type SpecSchedule
- type ThresholdCallback
- type ThresholdCallbackAsync
Examples ¶
Constants ¶
const JobRunEventsBuffer = 100
JobRunEventsBuffer is the number of job runs buffered by the channels of JobRunCreatedCh and JobRunCompletedCh, before new ones are dropped.
Variables ¶
var ErrCronNotRunning = errors.New("cron is not running")
ErrCronNotRunning is returned by Trigger when the cron is not running
var ErrEntryNotFound = errors.New("entry not found")
ErrEntryNotFound is returned when an entry ID does not exist
var ErrHookNotFound = errors.New("hook not found")
ErrHookNotFound is returned when a hook ID does not exist
var ErrIDAlreadyUsed = errors.New("id already used")
ErrIDAlreadyUsed is returned when adding an entry with the ID of an existing entry (see WithID)
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)
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)
var ErrUnsatisfiableSchedule = errors.New("schedule never activates")
ErrUnsatisfiableSchedule is returned when a spec never activates (eg: "0 0 30 2 *", February 30th)
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
var SecondParser = NewParser(Second | Minute | Hour | Dom | Month | DowOptional | Descriptor)
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
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 HookDisable ¶
func HookDisable(hook *hookStruct)
HookDisable disables a hook by setting its active status to false.
func NextN ¶ added in v1.0.0
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
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 ¶
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
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.
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 ¶
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
KeepJobsRunningOnStop makes Stop wait for the running jobs without cancelling their context. By default, Stop cancels the context of the running jobs.
func (*Builder) WithContext ¶
WithContext sets the base context for the Cron instance.
func (*Builder) WithIDFactory ¶
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 ¶
WithKeepCompletedRunsDur sets the duration to keep completed job runs before cleanup.
func (*Builder) WithLocation ¶
WithLocation sets the timezone location for the Cron instance.
func (*Builder) WithLogger ¶
WithLogger sets the logger for the Cron instance.
func (*Builder) WithMaxCompletedRunsPerEntry ¶ added in v0.2.0
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
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
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
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
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
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 ¶
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
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 ¶
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.
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) AddJobAt ¶ added in v1.0.0
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 ¶
AddJobStrict same as AddJob, but only accept a Job interface instead of IntoJob (any)
func (*Cron) CancelJobRun ¶
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 ¶
CompletedJobRunsFor returns all completed job runs for a specific entry. Returns ErrEntryNotFound if the entry doesn't exist.
func (*Cron) CompletedJobs ¶
CompletedJobs returns a list of all completed job runs across all entries
func (*Cron) Disable ¶
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
DisableByTag disables the entries having the given tag, and returns how many entries have the tag
func (*Cron) DisableHook ¶
DisableHook disables a previously enabled hook by its ID. It returns ErrHookNotFound if the hook does not exist.
func (*Cron) Enable ¶
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
EnableByTag enables the entries having the given tag, and returns how many entries have the tag
func (*Cron) EnableHook ¶
EnableHook enables a previously disabled hook by its ID. It returns ErrHookNotFound if the hook does not exist.
func (*Cron) EntriesByTag ¶ added in v1.0.0
EntriesByTag returns a snapshot of the entries having the given tag, sorted like Entries
func (*Cron) GetCleanupTS ¶
GetCleanupTS returns the timestamp of the last completed job runs cleanup
func (*Cron) GetJobRun ¶
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 ¶
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) JobRunCompletedCh ¶
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 ¶
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) NextActivations ¶ added in v1.0.0
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
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 ¶
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
RemoveByTag removes the entries having the given tag (as Remove does), and returns how many were removed
func (*Cron) RemoveHook ¶
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) RunNow ¶
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 ¶
RunningJobs returns a list of all currently running jobs across all entries
func (*Cron) RunningJobsFor ¶
RunningJobsFor returns all currently running jobs for a specific entry // Returns ErrEntryNotFound if the entry doesn't exist.
func (*Cron) SetCleanupInterval ¶
SetCleanupInterval sets the duration for keeping completed job runs before cleanup
func (*Cron) SetHookLabel ¶
SetHookLabel sets a hook's label. It returns ErrHookNotFound if the hook does not exist.
func (*Cron) SetLocation ¶
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
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
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) 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
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 ¶
UpdateLabel updates an entry's label. It returns ErrEntryNotFound if the entry does not exist.
func (*Cron) UpdateSchedule ¶
UpdateSchedule updates an entry's schedule with a new Schedule
func (*Cron) UpdateScheduleWithSpec ¶
UpdateScheduleWithSpec updates an entry's schedule by parsing a spec string
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) Job ¶
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 EntryOption ¶
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 FuncJobRunLoggerFactory ¶
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.
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 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 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.
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 ¶
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 ¶
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 ¶
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 SkipIfStillRunning ¶
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 WithJitter ¶
WithJitter add some random delay before running the job
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)
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.
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 ¶
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.
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")
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...
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 ¶
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 ¶
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.