Documentation
¶
Overview ¶
Package cron is an implementation of a job scheduler to run within a worker or a server.
It allows developers to configure flexible schedules to run jobs.
Index ¶
- Constants
- Variables
- func ConstBool(value bool) func() bool
- func ConstDuration(value time.Duration) func() time.Duration
- func ConstInt(value int) func() int
- func ConstLabels(labels map[string]string) func() map[string]string
- func FormatTime(t time.Time) string
- func IsContextCanceled(ctx context.Context) bool
- func IsJobAlreadyLoaded(err error) bool
- func IsJobAlreadyRunning(err error) bool
- func IsJobCanceled(err error) bool
- func IsJobNotFound(err error) bool
- func IsJobNotLoaded(err error) bool
- func IsWeekDay(day time.Weekday) bool
- func IsWeekendDay(day time.Weekday) bool
- func Max(t1, t2 time.Time) time.Time
- func Min(t1, t2 time.Time) time.Time
- func NewEventListener(listener func(context.Context, Event)) logger.Listener
- func NewJobInvocationID() string
- func Now() time.Time
- func SetDefault(jm *JobManager)
- func Since(t time.Time) time.Duration
- func WithJobInvocation(ctx context.Context, ji *JobInvocation) context.Context
- func WithJobManager(ctx context.Context, jm *JobManager) context.Context
- func WithJobParameterValues(ctx context.Context, values JobParameters) context.Context
- func WithJobScheduler(ctx context.Context, js *JobScheduler) context.Context
- type Action
- type BackgroundProvider
- type ConfigProvider
- type DailySchedule
- type DelaySchedule
- type Event
- type EventOption
- type ImmediateSchedule
- type IntervalSchedule
- type Job
- type JobBuilder
- type JobBuilderOption
- func OptJobAction(action func(context.Context) error) JobBuilderOption
- func OptJobBackground(provider func(context.Context) context.Context) JobBuilderOption
- func OptJobConfig(cfg JobConfig) JobBuilderOption
- func OptJobDisabled(disabled bool) JobBuilderOption
- func OptJobLabels(labels map[string]string) JobBuilderOption
- func OptJobName(name string) JobBuilderOption
- func OptJobOnBegin(handler func(context.Context)) JobBuilderOption
- func OptJobOnBroken(handler func(context.Context)) JobBuilderOption
- func OptJobOnCancellation(handler func(context.Context)) JobBuilderOption
- func OptJobOnComplete(handler func(context.Context)) JobBuilderOption
- func OptJobOnDisabled(handler func(context.Context)) JobBuilderOption
- func OptJobOnEnabled(handler func(context.Context)) JobBuilderOption
- func OptJobOnError(handler func(context.Context)) JobBuilderOption
- func OptJobOnFixed(handler func(context.Context)) JobBuilderOption
- func OptJobOnLoad(handler func(context.Context) error) JobBuilderOption
- func OptJobOnSuccess(handler func(context.Context)) JobBuilderOption
- func OptJobOnUnload(handler func(context.Context) error) JobBuilderOption
- func OptJobSchedule(schedule Schedule) JobBuilderOption
- func OptJobShutdownGracePeriod(d time.Duration) JobBuilderOption
- func OptJobTimeout(d time.Duration) JobBuilderOption
- type JobConfig
- type JobInvocation
- type JobInvocationStatus
- type JobLifecycle
- type JobManager
- func (jm *JobManager) Background() context.Context
- func (jm *JobManager) CancelJob(jobName string) (err error)
- func (jm *JobManager) DisableJobs(jobNames ...string) error
- func (jm *JobManager) EnableJobs(jobNames ...string) error
- func (jm *JobManager) HasJob(jobName string) (hasJob bool)
- func (jm *JobManager) IsJobDisabled(jobName string) (value bool)
- func (jm *JobManager) IsJobRunning(jobName string) (isRunning bool)
- func (jm *JobManager) Job(jobName string) (job *JobScheduler, err error)
- func (jm *JobManager) LoadJobs(jobs ...Job) error
- func (jm *JobManager) RunJob(jobName string) (*JobInvocation, <-chan struct{}, error)
- func (jm *JobManager) RunJobContext(ctx context.Context, jobName string) (*JobInvocation, <-chan struct{}, error)
- func (jm *JobManager) Start() error
- func (jm *JobManager) StartAsync() error
- func (jm *JobManager) State() JobManagerState
- func (jm *JobManager) Stop() error
- func (jm *JobManager) UnloadJobs(jobNames ...string) error
- type JobManagerOption
- type JobManagerState
- type JobParameters
- type JobScheduler
- func (js *JobScheduler) Background() context.Context
- func (js *JobScheduler) CanBeScheduled() bool
- func (js *JobScheduler) Cancel() error
- func (js *JobScheduler) Config() JobConfig
- func (js *JobScheduler) Current() (current *JobInvocation)
- func (js *JobScheduler) Description() string
- func (js *JobScheduler) Disable()
- func (js *JobScheduler) Disabled() bool
- func (js *JobScheduler) Enable()
- func (js *JobScheduler) IsIdle() (isIdle bool)
- func (js *JobScheduler) Labels() map[string]string
- func (js *JobScheduler) Last() (last *JobInvocation)
- func (js *JobScheduler) Lifecycle() JobLifecycle
- func (js *JobScheduler) Name() string
- func (js *JobScheduler) NotifyStarted() <-chan struct{}
- func (js *JobScheduler) NotifyStopped() <-chan struct{}
- func (js *JobScheduler) OnLoad(ctx context.Context) error
- func (js *JobScheduler) OnUnload(ctx context.Context) error
- func (js *JobScheduler) Run()
- func (js *JobScheduler) RunAsync() (*JobInvocation, <-chan struct{}, error)
- func (js *JobScheduler) RunAsyncContext(ctx context.Context) (*JobInvocation, <-chan struct{}, error)
- func (js *JobScheduler) RunContext(ctx context.Context)
- func (js *JobScheduler) RunLoop()
- func (js *JobScheduler) SetCurrent(ji *JobInvocation)
- func (js *JobScheduler) SetLast(ji *JobInvocation)
- func (js *JobScheduler) Start() error
- func (js *JobScheduler) State() JobSchedulerState
- func (js *JobScheduler) Stop() error
- type JobSchedulerOption
- type JobSchedulerState
- type JobSchedulersByJobNameAsc
- type LifecycleProvider
- type NeverSchedule
- type OnTheHourAtUTCSchedule
- type OnceAtUTCSchedule
- type Schedule
- func DailyAtUTC(hour, minute, second int) Schedule
- func EveryHourAtUTC(minute, second int) Schedule
- func EveryHourOnTheHour() Schedule
- func ParseSchedule(cronString string) (schedule Schedule, err error)
- func WeekdaysAtUTC(hour, minute, second int) Schedule
- func WeekendsAtUTC(hour, minute, second int) Schedule
- func WeeklyAtUTC(hour, minute, second int, days ...time.Weekday) Schedule
- type ScheduleFunc
- type ScheduleProvider
- type StringSchedule
- type TimesSchedule
- type TraceFinisher
- type Tracer
Constants ¶
const ( DefaultTimeout time.Duration = 0 DefaultHistoryRestoreTimeout = 5 * time.Second DefaultShutdownGracePeriod time.Duration = 0 )
Constats and defaults
const ( // DefaultDisabled is a default. DefaultDisabled = false // DefaultShouldSkipLoggerListeners is a default. DefaultShouldSkipLoggerListeners = false // DefaultShouldSkipLoggerOutput is a default. DefaultShouldSkipLoggerOutput = false )
const ( // FlagBegin is an event flag. FlagBegin = "cron.begin" // FlagComplete is an event flag. FlagComplete = "cron.complete" // FlagSuccess is an event flag. FlagSuccess = "cron.success" // FlagErrored is an event flag. FlagErrored = "cron.errored" // FlagCanceled is an event flag. FlagCanceled = "cron.canceled" // FlagBroken is an event flag. FlagBroken = "cron.broken" // FlagFixed is an event flag. FlagFixed = "cron.fixed" // FlagEnabled is an event flag. FlagEnabled = "cron.enabled" // FlagDisabled is an event flag. FlagDisabled = "cron.disabled" )
const ( // ErrJobNotLoaded is a common error. ErrJobNotLoaded ex.Class = "job not loaded" // ErrJobAlreadyLoaded is a common error. ErrJobAlreadyLoaded ex.Class = "job already loaded" // ErrJobNotFound is a common error. ErrJobNotFound ex.Class = "job not found" // ErrJobCanceled is a common error. ErrJobCanceled ex.Class = "job canceled" // ErrJobAlreadyRunning is a common error. ErrJobAlreadyRunning ex.Class = "job already running" )
const ( ErrStringScheduleInvalid ex.Class = "cron: schedule string invalid" ErrStringScheduleComponents ex.Class = "cron: must have at least (5) components space delimited; ex: '0 0 * * * * *'" ErrStringScheduleValueOutOfRange ex.Class = "cron: string schedule part out of range" ErrStringScheduleInvalidRange ex.Class = "cron: range (from-to) invalid" )
Error Constants
const ( StringScheduleImmediately = "@immediately" StringScheduleDelay = "@delay" StringScheduleImmediatelyThen = "@immediately-then" StringScheduleEvery = "@every" StringScheduleOnceAt = "@once-at" StringScheduleNever = "@never" )
String schedule constants
const ( StringScheduleShorthandAnnually = "@annually" StringScheduleShorthandYearly = "@yearly" StringScheduleShorthandMonthly = "@monthly" StringScheduleShorthandWeekly = "@weekly" StringScheduleShorthandDaily = "@daily" StringScheduleShorthandHourly = "@hourly" )
String schedule shorthands labels
const ( // AllDaysMask is a bitmask of all the days of the week. AllDaysMask = 1<<uint(time.Sunday) | 1<<uint(time.Monday) | 1<<uint(time.Tuesday) | 1<<uint(time.Wednesday) | 1<<uint(time.Thursday) | 1<<uint(time.Friday) | 1<<uint(time.Saturday) // WeekDaysMask is a bitmask of all the weekdays of the week. WeekDaysMask = 1<<uint(time.Monday) | 1<<uint(time.Tuesday) | 1<<uint(time.Wednesday) | 1<<uint(time.Thursday) | 1<<uint(time.Friday) //WeekendDaysMask is a bitmask of the weekend days of the week. WeekendDaysMask = 1<<uint(time.Sunday) | 1<<uint(time.Saturday) )
NOTE: we have to use shifts here because in their infinite wisdom google didn't make these values powers of two for masking
Variables ¶
var ( // DaysOfWeek are all the time.Weekday in an array for utility purposes. DaysOfWeek = []time.Weekday{ time.Sunday, time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, time.Saturday, } // WeekDays are the business time.Weekday in an array. WeekDays = []time.Weekday{ time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, } // WeekWeekEndDaysDays are the weekend time.Weekday in an array. WeekendDays = []time.Weekday{ time.Sunday, time.Saturday, } // Epoch is unix epoch saved for utility purposes. Epoch = time.Unix(0, 0) // Zero is different than epoch in that it is the "unset" value for a time // where Epoch is a valid date. Nominally it is `time.Time{}`. Zero = time.Time{} )
NOTE: time.Zero()? what's that?
var ( StringScheduleShorthands = map[string]string{ StringScheduleShorthandAnnually: "0 0 0 1 1 * *", StringScheduleShorthandYearly: "0 0 0 1 1 * *", StringScheduleShorthandMonthly: "0 0 0 1 * * *", StringScheduleShorthandDaily: "0 0 0 * * * *", StringScheduleShorthandHourly: "0 0 * * * * *", } )
String schedule shorthand values
Functions ¶
func ConstDuration ¶ added in v1.20201204.1
ConstDuration returns a value provider for a constant.
func ConstLabels ¶ added in v1.20201204.1
ConstLabels returns a value provider for a constant.
func IsContextCanceled ¶ added in v1.20210819.9
IsContextCanceled check if a job is canceled
func IsJobAlreadyLoaded ¶
IsJobAlreadyLoaded returns if the error is a job already loaded error.
func IsJobAlreadyRunning ¶ added in v1.20201204.1
IsJobAlreadyRunning returns if the error is a task not found error.
func IsJobCanceled ¶ added in v1.20210819.9
IsJobCanceled returns if the error is a task not found error.
func IsJobNotFound ¶ added in v0.3.2
IsJobNotFound returns if the error is a task not found error.
func IsJobNotLoaded ¶
IsJobNotLoaded returns if the error is a job not loaded error.
func IsWeekendDay ¶
IsWeekendDay returns if the day is a monday->friday.
func NewEventListener ¶
NewEventListener returns a new event listener.
func NewJobInvocationID ¶ added in v0.3.2
func NewJobInvocationID() string
NewJobInvocationID returns a new pseudo-unique job invocation identifier.
func WithJobInvocation ¶ added in v0.3.2
func WithJobInvocation(ctx context.Context, ji *JobInvocation) context.Context
WithJobInvocation adds job invocation to a context.
func WithJobManager ¶ added in v1.20201204.1
func WithJobManager(ctx context.Context, jm *JobManager) context.Context
WithJobManager adds a job manager to a context.
func WithJobParameterValues ¶ added in v1.20201204.1
func WithJobParameterValues(ctx context.Context, values JobParameters) context.Context
WithJobParameterValues adds job invocation parameter values to a context.
func WithJobScheduler ¶ added in v1.20210701.2
func WithJobScheduler(ctx context.Context, js *JobScheduler) context.Context
WithJobScheduler adds a job scheduler to a context.
Types ¶
type BackgroundProvider ¶ added in v1.20201204.1
BackgroundProvider is a type that returns a base context based on a parent.
type ConfigProvider ¶ added in v1.20201204.1
type ConfigProvider interface {
Config() JobConfig
}
ConfigProvider is a type that returns a job config.
type DailySchedule ¶
DailySchedule is a schedule that fires every day that satisfies the DayOfWeekMask at the given TimeOfDayUTC.
func (DailySchedule) Next ¶ added in v1.20201204.1
func (ds DailySchedule) Next(after time.Time) time.Time
Next implements Schedule.
func (DailySchedule) String ¶ added in v1.20201204.1
func (ds DailySchedule) String() string
type DelaySchedule ¶ added in v1.20210701.2
type DelaySchedule struct {
// contains filtered or unexported fields
}
DelaySchedule wraps a schedule with a delay.
func Delay ¶ added in v1.20210701.2
func Delay(d time.Duration, then Schedule) *DelaySchedule
Delay returns a composite schedule that delays a given schedule by a given duration.
func (*DelaySchedule) Next ¶ added in v1.20210701.2
func (ds *DelaySchedule) Next(after time.Time) time.Time
Next implements Schedule.
func (*DelaySchedule) String ¶ added in v1.20210701.2
func (ds *DelaySchedule) String() string
String implements a string schedule.
type Event ¶
type Event struct { Flag string JobName string JobInvocation string Err error Elapsed time.Duration }
Event is an event.
func NewEvent ¶
func NewEvent(flag, jobName string, options ...EventOption) Event
NewEvent creates a new event with a given set of optional options.
type EventOption ¶ added in v1.20201204.1
type EventOption func(*Event)
EventOption is an option for an Event.
func OptEventElapsed ¶ added in v1.20201204.1
func OptEventElapsed(elapsed time.Duration) EventOption
OptEventElapsed sets a field.
func OptEventErr ¶ added in v1.20201204.1
func OptEventErr(err error) EventOption
OptEventErr sets a field.
func OptEventJobInvocation ¶ added in v1.20201204.1
func OptEventJobInvocation(jobInvocation string) EventOption
OptEventJobInvocation sets a field.
type ImmediateSchedule ¶
type ImmediateSchedule struct {
// contains filtered or unexported fields
}
ImmediateSchedule fires immediately with an optional continuation schedule.
func Immediately ¶
func Immediately() *ImmediateSchedule
Immediately Returns a schedule that causes a job to run immediately on start, with an optional subsequent schedule.
func (*ImmediateSchedule) Next ¶ added in v1.20201204.1
func (i *ImmediateSchedule) Next(after time.Time) time.Time
Next implements Schedule.
func (*ImmediateSchedule) String ¶ added in v1.20201204.1
func (i *ImmediateSchedule) String() string
String returns a string representation of the schedul.e
func (*ImmediateSchedule) Then ¶
func (i *ImmediateSchedule) Then(then Schedule) Schedule
Then allows you to specify a subsequent schedule after the first run.
type IntervalSchedule ¶
IntervalSchedule is as chedule that fires every given interval with an optional start delay.
func Every ¶
func Every(interval time.Duration) IntervalSchedule
Every returns a schedule that fires every given interval.
func EveryHour ¶
func EveryHour() IntervalSchedule
EveryHour returns a schedule that fire every hour.
func EveryMinute ¶
func EveryMinute() IntervalSchedule
EveryMinute returns a schedule that fires every minute.
func EverySecond ¶
func EverySecond() IntervalSchedule
EverySecond returns a schedule that fires every second.
func (IntervalSchedule) Next ¶ added in v1.20201204.1
func (i IntervalSchedule) Next(after time.Time) time.Time
Next implements Schedule.
func (IntervalSchedule) String ¶ added in v1.20201204.1
func (i IntervalSchedule) String() string
String returns a string representation of the schedule.
type JobBuilder ¶ added in v0.3.2
type JobBuilder struct { JobName string JobConfig JobConfig JobLifecycle JobLifecycle JobAction Action JobScheduleProvider func() Schedule BackgroundProvider func(context.Context) context.Context }
JobBuilder allows for job creation w/o a fully formed struct.
func NewJob ¶
func NewJob(options ...JobBuilderOption) *JobBuilder
NewJob returns a new job builder.
func (*JobBuilder) Background ¶ added in v1.20210701.2
func (jb *JobBuilder) Background(ctx context.Context) context.Context
Background implements BackgroundProvider.
func (*JobBuilder) Config ¶ added in v1.20201204.1
func (jb *JobBuilder) Config() JobConfig
Config returns the job config.
func (*JobBuilder) Execute ¶ added in v0.3.2
func (jb *JobBuilder) Execute(ctx context.Context) error
Execute runs the job action if it's set.
func (*JobBuilder) Lifecycle ¶ added in v1.20201204.1
func (jb *JobBuilder) Lifecycle() JobLifecycle
Lifecycle returns the job lifecycle hooks.
func (*JobBuilder) Name ¶ added in v0.3.2
func (jb *JobBuilder) Name() string
Name returns the job name.
func (*JobBuilder) Schedule ¶ added in v0.3.2
func (jb *JobBuilder) Schedule() Schedule
Schedule returns the job schedule if a provider is set.
type JobBuilderOption ¶ added in v1.20201204.1
type JobBuilderOption func(*JobBuilder)
JobBuilderOption is a job builder option.
func OptJobAction ¶ added in v1.20201204.1
func OptJobAction(action func(context.Context) error) JobBuilderOption
OptJobAction sets the job action.
func OptJobBackground ¶ added in v1.20210701.2
func OptJobBackground(provider func(context.Context) context.Context) JobBuilderOption
OptJobBackground sets the background provider.
func OptJobConfig ¶ added in v1.20201204.1
func OptJobConfig(cfg JobConfig) JobBuilderOption
OptJobConfig sets the job config.
func OptJobDisabled ¶ added in v1.20201204.1
func OptJobDisabled(disabled bool) JobBuilderOption
OptJobDisabled is a job builder sets the job timeout provder.
func OptJobLabels ¶ added in v1.20201204.1
func OptJobLabels(labels map[string]string) JobBuilderOption
OptJobLabels is a job builder sets the job labels.
func OptJobName ¶ added in v1.20201204.1
func OptJobName(name string) JobBuilderOption
OptJobName sets the job name.
func OptJobOnBegin ¶ added in v1.20201204.1
func OptJobOnBegin(handler func(context.Context)) JobBuilderOption
OptJobOnBegin sets a lifecycle hook.
func OptJobOnBroken ¶ added in v1.20201204.1
func OptJobOnBroken(handler func(context.Context)) JobBuilderOption
OptJobOnBroken sets a lifecycle hook.
func OptJobOnCancellation ¶ added in v1.20201204.1
func OptJobOnCancellation(handler func(context.Context)) JobBuilderOption
OptJobOnCancellation sets the on cancellation lifecycle hook.
func OptJobOnComplete ¶ added in v1.20201204.1
func OptJobOnComplete(handler func(context.Context)) JobBuilderOption
OptJobOnComplete sets a lifecycle hook.
func OptJobOnDisabled ¶ added in v1.20201204.1
func OptJobOnDisabled(handler func(context.Context)) JobBuilderOption
OptJobOnDisabled sets a lifecycle hook.
func OptJobOnEnabled ¶ added in v1.20201204.1
func OptJobOnEnabled(handler func(context.Context)) JobBuilderOption
OptJobOnEnabled sets a lifecycle hook.
func OptJobOnError ¶ added in v1.20201204.1
func OptJobOnError(handler func(context.Context)) JobBuilderOption
OptJobOnError sets a lifecycle hook.
func OptJobOnFixed ¶ added in v1.20201204.1
func OptJobOnFixed(handler func(context.Context)) JobBuilderOption
OptJobOnFixed sets a lifecycle hook.
func OptJobOnLoad ¶ added in v1.20210701.2
func OptJobOnLoad(handler func(context.Context) error) JobBuilderOption
OptJobOnLoad sets a lifecycle hook.
func OptJobOnSuccess ¶ added in v1.20201204.1
func OptJobOnSuccess(handler func(context.Context)) JobBuilderOption
OptJobOnSuccess sets a lifecycle hook.
func OptJobOnUnload ¶ added in v1.20210701.2
func OptJobOnUnload(handler func(context.Context) error) JobBuilderOption
OptJobOnUnload sets a lifecycle hook.
func OptJobSchedule ¶ added in v1.20201204.1
func OptJobSchedule(schedule Schedule) JobBuilderOption
OptJobSchedule is a job builder sets the job schedule provder.
func OptJobShutdownGracePeriod ¶ added in v1.20201204.1
func OptJobShutdownGracePeriod(d time.Duration) JobBuilderOption
OptJobShutdownGracePeriod is a job builder sets the job shutdown grace period provder.
func OptJobTimeout ¶ added in v1.20201204.1
func OptJobTimeout(d time.Duration) JobBuilderOption
OptJobTimeout is a job builder sets the job timeout provder.
type JobConfig ¶ added in v1.20201204.1
type JobConfig struct { // Disabled determines if the job should be automatically scheduled or not. Disabled *bool `json:"disabled" yaml:"disabled"` // Description is an optional string to describe what the job does. Description string `json:"description" yaml:"description"` // Labels define extra metadata that can be used to filter jobs. Labels map[string]string `json:"labels" yaml:"labels"` // ParameterValues act as default parameters for a given job. ParameterValues JobParameters `json:"parameterValues" yaml:"parameterValues"` // Timeout represents the abort threshold for the job. Timeout time.Duration `json:"timeout" yaml:"timeout"` // ShutdownGracePeriod represents the time a job is given to clean itself up. ShutdownGracePeriod time.Duration `json:"shutdownGracePeriod" yaml:"shutdownGracePeriod"` // SkipLoggerTrigger skips triggering logger events if it is set to true. SkipLoggerTrigger bool `json:"skipLoggerTrigger" yaml:"skipLoggerTrigger"` }
JobConfig is a configuration set for a job.
func (JobConfig) DisabledOrDefault ¶ added in v1.20201204.1
DisabledOrDefault returns a value or a default.
func (JobConfig) ShutdownGracePeriodOrDefault ¶ added in v1.20201204.1
ShutdownGracePeriodOrDefault returns a value or a default.
func (JobConfig) TimeoutOrDefault ¶ added in v1.20201204.1
TimeoutOrDefault returns a value or a default.
type JobInvocation ¶ added in v0.3.2
type JobInvocation struct { ID string `json:"id"` JobName string `json:"jobName"` Started time.Time `json:"started"` Complete time.Time `json:"complete"` Err error `json:"err"` Parameters JobParameters `json:"parameters"` Status JobInvocationStatus `json:"status"` State interface{} `json:"-"` Cancel context.CancelFunc `json:"-"` }
JobInvocation is metadata for a job invocation (or instance of a job running).
func GetJobInvocation ¶ added in v0.3.2
func GetJobInvocation(ctx context.Context) *JobInvocation
GetJobInvocation gets the job invocation from a given context.
func NewJobInvocation ¶ added in v1.20201204.1
func NewJobInvocation(jobName string) *JobInvocation
NewJobInvocation returns a new job invocation.
func (*JobInvocation) Clone ¶ added in v1.20201204.1
func (ji *JobInvocation) Clone() *JobInvocation
Clone clones the job invocation.
func (*JobInvocation) Elapsed ¶ added in v0.3.2
func (ji *JobInvocation) Elapsed() time.Duration
Elapsed returns the elapsed time for the invocation.
type JobInvocationStatus ¶ added in v1.20201204.1
type JobInvocationStatus string
JobInvocationStatus is a job status.
const ( JobInvocationStatusIdle JobInvocationStatus = "idle" JobInvocationStatusRunning JobInvocationStatus = "running" JobInvocationStatusCanceled JobInvocationStatus = "canceled" JobInvocationStatusErrored JobInvocationStatus = "errored" JobInvocationStatusSuccess JobInvocationStatus = "success" )
JobInvocationState values.
type JobLifecycle ¶ added in v1.20201204.1
type JobLifecycle struct { // OnLoad is called when the job is loaded into the job manager. OnLoad func(context.Context) error // OnUnload is called when the job is unloaded from the manager // or the job manager is stopped. OnUnload func(context.Context) error // OnBegin fires whenever a job is started. OnBegin func(context.Context) // OnComplete fires whenever a job finishes, regardless of status. OnComplete func(context.Context) // OnCancellation is called if the job is canceled explicitly // or it sets a timeout in the .Config() and exceeds that timeout. OnCancellation func(context.Context) // OnError is called if the job returns an error or panics during // execution, but will not be called if the job is canceled. OnError func(context.Context) // OnSuccess is called if the job completes without an error. OnSuccess func(context.Context) // OnBroken is called if the job errors after having completed successfully // the previous invocation. OnBroken func(context.Context) // OnFixed is called if the job completes successfully after having // returned an error on the previous invocation. OnFixed func(context.Context) // OnEnabled is called if the job is explicitly enabled. OnEnabled func(context.Context) // OnDisabled is called if the job is explicitly disabled. OnDisabled func(context.Context) }
JobLifecycle is a suite of lifeycle hooks you can set for a given job.
type JobManager ¶
type JobManager struct { sync.Mutex Latch *async.Latch BaseContext context.Context Tracer Tracer Log logger.Log Started time.Time Stopped time.Time Jobs map[string]*JobScheduler }
JobManager is the main orchestration and job management object.
func Default ¶
func Default() *JobManager
Default returns a shared instance of a JobManager. If unset, it will initialize it with `New()`.
func GetJobManager ¶ added in v1.20201204.1
func GetJobManager(ctx context.Context) *JobManager
GetJobManager gets a JobManager off a context.
func (*JobManager) Background ¶ added in v1.20220129.5
func (jm *JobManager) Background() context.Context
Background returns the BaseContext or context.Background().
func (*JobManager) CancelJob ¶ added in v0.3.2
func (jm *JobManager) CancelJob(jobName string) (err error)
CancelJob cancels (sends the cancellation signal) to a running job.
func (*JobManager) DisableJobs ¶
func (jm *JobManager) DisableJobs(jobNames ...string) error
DisableJobs disables a variadic list of job names.
func (*JobManager) EnableJobs ¶
func (jm *JobManager) EnableJobs(jobNames ...string) error
EnableJobs enables a variadic list of job names.
func (*JobManager) HasJob ¶
func (jm *JobManager) HasJob(jobName string) (hasJob bool)
HasJob returns if a jobName is loaded or not.
func (*JobManager) IsJobDisabled ¶ added in v0.3.2
func (jm *JobManager) IsJobDisabled(jobName string) (value bool)
IsJobDisabled returns if a job is disabled.
func (*JobManager) IsJobRunning ¶ added in v0.3.2
func (jm *JobManager) IsJobRunning(jobName string) (isRunning bool)
IsJobRunning returns if a job is currently running.
func (*JobManager) Job ¶
func (jm *JobManager) Job(jobName string) (job *JobScheduler, err error)
Job returns a job metadata by name.
func (*JobManager) LoadJobs ¶
func (jm *JobManager) LoadJobs(jobs ...Job) error
LoadJobs loads a variadic list of jobs.
func (*JobManager) RunJob ¶
func (jm *JobManager) RunJob(jobName string) (*JobInvocation, <-chan struct{}, error)
RunJob runs a job by jobName on demand.
func (*JobManager) RunJobContext ¶ added in v1.20201204.1
func (jm *JobManager) RunJobContext(ctx context.Context, jobName string) (*JobInvocation, <-chan struct{}, error)
RunJobContext runs a job by jobName on demand with a given context.
func (*JobManager) Start ¶
func (jm *JobManager) Start() error
Start starts the job manager and blocks.
func (*JobManager) StartAsync ¶ added in v1.20201204.1
func (jm *JobManager) StartAsync() error
StartAsync starts the job manager and the loaded jobs. It does not block.
func (*JobManager) State ¶ added in v1.20201204.1
func (jm *JobManager) State() JobManagerState
State returns the job manager state.
func (*JobManager) Stop ¶
func (jm *JobManager) Stop() error
Stop stops the schedule runner for a JobManager.
func (*JobManager) UnloadJobs ¶ added in v1.20201204.1
func (jm *JobManager) UnloadJobs(jobNames ...string) error
UnloadJobs removes jobs from the manager and stops them.
type JobManagerOption ¶ added in v1.20201204.1
type JobManagerOption func(*JobManager)
JobManagerOption is a job manager option.
func OptBaseContext ¶ added in v1.20201204.1
func OptBaseContext(ctx context.Context) JobManagerOption
OptBaseContext sets the job manager base context.
func OptLog ¶ added in v1.20201204.1
func OptLog(log logger.Log) JobManagerOption
OptLog sets the job manager logger.
func OptTracer ¶ added in v1.20201204.1
func OptTracer(tracer Tracer) JobManagerOption
OptTracer sets the job manager tracer.
type JobManagerState ¶ added in v1.20201204.1
type JobManagerState string
JobManagerState is a job manager status.
const ( JobManagerStateUnknown JobManagerState = "unknown" JobManagerStateRunning JobManagerState = "started" JobManagerStateStopped JobManagerState = "stopped" )
JobManagerState values.
type JobParameters ¶ added in v1.20201204.1
JobParameters is a loose association to map[string]string.
func GetJobParameterValues ¶ added in v1.20201204.1
func GetJobParameterValues(ctx context.Context) JobParameters
GetJobParameterValues gets parameter values from a given context.
func MergeJobParameterValues ¶ added in v1.20201204.1
func MergeJobParameterValues(values ...JobParameters) JobParameters
MergeJobParameterValues merges values from many sources. The order is important for which value set's keys take precedence.
type JobScheduler ¶ added in v1.20201204.1
type JobScheduler struct { Latch *async.Latch Job Job JobConfig JobConfig JobSchedule Schedule JobLifecycle JobLifecycle BaseContext context.Context Tracer Tracer Log logger.Log NextRuntime time.Time // contains filtered or unexported fields }
JobScheduler is a job instance.
func GetJobScheduler ¶ added in v1.20210701.2
func GetJobScheduler(ctx context.Context) *JobScheduler
GetJobScheduler gets a JobScheduler off a context.
func NewJobScheduler ¶ added in v1.20201204.1
func NewJobScheduler(job Job, options ...JobSchedulerOption) *JobScheduler
NewJobScheduler returns a job scheduler for a given job.
func (*JobScheduler) Background ¶ added in v1.20201204.1
func (js *JobScheduler) Background() context.Context
Background returns the job scheduler base context.
It should be used as the root context for _any_ operations.
func (*JobScheduler) CanBeScheduled ¶ added in v1.20201204.1
func (js *JobScheduler) CanBeScheduled() bool
CanBeScheduled returns if a job will be triggered automatically and isn't already in flight and set to be serial.
func (*JobScheduler) Cancel ¶ added in v1.20201204.1
func (js *JobScheduler) Cancel() error
Cancel stops all running invocations.
func (*JobScheduler) Config ¶ added in v1.20201204.1
func (js *JobScheduler) Config() JobConfig
Config returns the job config provided by a job or an empty config.
func (*JobScheduler) Current ¶ added in v1.20201204.1
func (js *JobScheduler) Current() (current *JobInvocation)
Current returns the current job invocation.
func (*JobScheduler) Description ¶ added in v1.20201204.1
func (js *JobScheduler) Description() string
Description returns the description.
func (*JobScheduler) Disable ¶ added in v1.20201204.1
func (js *JobScheduler) Disable()
Disable sets the job as disabled.
func (*JobScheduler) Disabled ¶ added in v1.20201204.1
func (js *JobScheduler) Disabled() bool
Disabled returns if the job is disabled or not.
func (*JobScheduler) Enable ¶ added in v1.20201204.1
func (js *JobScheduler) Enable()
Enable sets the job as enabled.
func (*JobScheduler) IsIdle ¶ added in v1.20201204.1
func (js *JobScheduler) IsIdle() (isIdle bool)
IsIdle returns if the job is not currently running.
func (*JobScheduler) Labels ¶ added in v1.20201204.1
func (js *JobScheduler) Labels() map[string]string
Labels returns the job labels, including automatically added ones like `name`.
func (*JobScheduler) Last ¶ added in v1.20201204.1
func (js *JobScheduler) Last() (last *JobInvocation)
Last returns the last job invocation.
func (*JobScheduler) Lifecycle ¶ added in v1.20201204.1
func (js *JobScheduler) Lifecycle() JobLifecycle
Lifecycle returns job lifecycle steps or an empty set.
func (*JobScheduler) Name ¶ added in v1.20201204.1
func (js *JobScheduler) Name() string
Name returns the job name.
func (*JobScheduler) NotifyStarted ¶ added in v1.20201204.1
func (js *JobScheduler) NotifyStarted() <-chan struct{}
NotifyStarted notifies the job scheduler has started.
func (*JobScheduler) NotifyStopped ¶ added in v1.20201204.1
func (js *JobScheduler) NotifyStopped() <-chan struct{}
NotifyStopped notifies the job scheduler has stopped.
func (*JobScheduler) OnLoad ¶ added in v1.20201204.1
func (js *JobScheduler) OnLoad(ctx context.Context) error
OnLoad triggers the on load even on the job lifecycle handler.
func (*JobScheduler) OnUnload ¶ added in v1.20201204.1
func (js *JobScheduler) OnUnload(ctx context.Context) error
OnUnload triggers the on unload even on the job lifecycle handler.
func (*JobScheduler) Run ¶ added in v1.20201204.1
func (js *JobScheduler) Run()
Run forces the job to run. This call will block.
func (*JobScheduler) RunAsync ¶ added in v1.20201204.1
func (js *JobScheduler) RunAsync() (*JobInvocation, <-chan struct{}, error)
RunAsync starts a job invocation with the BaseContext the root context.
func (*JobScheduler) RunAsyncContext ¶ added in v1.20201204.1
func (js *JobScheduler) RunAsyncContext(ctx context.Context) (*JobInvocation, <-chan struct{}, error)
RunAsyncContext starts a job invocation with a given context.
func (*JobScheduler) RunContext ¶ added in v1.20201204.1
func (js *JobScheduler) RunContext(ctx context.Context)
RunContext runs a job with a given context as the root context.
func (*JobScheduler) RunLoop ¶ added in v1.20201204.1
func (js *JobScheduler) RunLoop()
RunLoop is the main scheduler loop. This call blocks. It alarms on the next runtime and forks a new routine to run the job. It can be aborted with the scheduler's async.Latch, or calling `.Stop()`. If this function exits for any reason, it will mark the scheduler as stopped.
func (*JobScheduler) SetCurrent ¶ added in v1.20201204.1
func (js *JobScheduler) SetCurrent(ji *JobInvocation)
SetCurrent sets the current invocation, it is useful for tests etc.
func (*JobScheduler) SetLast ¶ added in v1.20201204.1
func (js *JobScheduler) SetLast(ji *JobInvocation)
SetLast sets the last invocation, it is useful for tests etc.
func (*JobScheduler) Start ¶ added in v1.20201204.1
func (js *JobScheduler) Start() error
Start starts the scheduler. This call blocks.
func (*JobScheduler) State ¶ added in v1.20201204.1
func (js *JobScheduler) State() JobSchedulerState
State returns the job scheduler state.
func (*JobScheduler) Stop ¶ added in v1.20201204.1
func (js *JobScheduler) Stop() error
Stop stops the scheduler.
type JobSchedulerOption ¶ added in v1.20201204.1
type JobSchedulerOption func(*JobScheduler)
JobSchedulerOption is an option for job schedulers.
func OptJobSchedulerBaseContext ¶ added in v1.20201204.1
func OptJobSchedulerBaseContext(ctx context.Context) JobSchedulerOption
OptJobSchedulerBaseContext sets the job scheduler BaseContext.
func OptJobSchedulerLog ¶ added in v1.20201204.1
func OptJobSchedulerLog(log logger.Log) JobSchedulerOption
OptJobSchedulerLog sets the job scheduler logger.
func OptJobSchedulerTracer ¶ added in v1.20201204.1
func OptJobSchedulerTracer(tracer Tracer) JobSchedulerOption
OptJobSchedulerTracer sets the job scheduler tracer.
type JobSchedulerState ¶ added in v1.20201204.1
type JobSchedulerState string
JobSchedulerState is a job manager status.
const ( JobSchedulerStateUnknown JobSchedulerState = "unknown" JobSchedulerStateRunning JobSchedulerState = "started" JobSchedulerStateStopped JobSchedulerState = "stopped" )
JobManagerState values.
type JobSchedulersByJobNameAsc ¶ added in v1.20201204.1
type JobSchedulersByJobNameAsc []*JobScheduler
JobSchedulersByJobNameAsc is a wrapper that sorts job schedulers by the job name ascending.
func (JobSchedulersByJobNameAsc) Len ¶ added in v1.20201204.1
func (s JobSchedulersByJobNameAsc) Len() int
Len implements sorter.
func (JobSchedulersByJobNameAsc) Less ¶ added in v1.20201204.1
func (s JobSchedulersByJobNameAsc) Less(i, j int) bool
Less implements sorter.
func (JobSchedulersByJobNameAsc) Swap ¶ added in v1.20201204.1
func (s JobSchedulersByJobNameAsc) Swap(i, j int)
Swap implements sorter.
type LifecycleProvider ¶ added in v1.20201204.1
type LifecycleProvider interface {
Lifecycle() JobLifecycle
}
LifecycleProvider is a job that provides lifecycle hooks.
type NeverSchedule ¶ added in v1.20210701.2
type NeverSchedule struct{}
NeverSchedule is a schedule that never runs.
func (NeverSchedule) Next ¶ added in v1.20210701.2
func (ns NeverSchedule) Next(_ time.Time) time.Time
Next implements Schedule
func (NeverSchedule) String ¶ added in v1.20210701.2
func (ns NeverSchedule) String() string
String implements fmt.Stringer.
type OnTheHourAtUTCSchedule ¶ added in v1.20201204.1
OnTheHourAtUTCSchedule is a schedule that fires every hour on the given minute.
func (OnTheHourAtUTCSchedule) Next ¶ added in v1.20201204.1
func (o OnTheHourAtUTCSchedule) Next(after time.Time) time.Time
Next implements the chronometer Schedule api.
func (OnTheHourAtUTCSchedule) String ¶ added in v1.20201204.1
func (o OnTheHourAtUTCSchedule) String() string
String returns a string representation of the schedule.
type OnceAtUTCSchedule ¶ added in v0.3.2
OnceAtUTCSchedule is a schedule.
func OnceAtUTC ¶ added in v0.3.2
func OnceAtUTC(t time.Time) OnceAtUTCSchedule
OnceAtUTC returns a schedule that fires once at a given time. It will never fire again unless reloaded.
func (OnceAtUTCSchedule) Next ¶ added in v1.20201204.1
func (oa OnceAtUTCSchedule) Next(after time.Time) time.Time
Next returns the next runtime.
func (OnceAtUTCSchedule) String ¶ added in v1.20201204.1
func (oa OnceAtUTCSchedule) String() string
String returns a string representation of the schedule.
type Schedule ¶
type Schedule interface { // GetNextRuntime should return the next runtime after a given previous runtime. If `after` is time.Time{} it should be assumed // the job hasn't run yet. If time.Time{} is returned by the schedule it is inferred that the job should not run again. Next(time.Time) time.Time }
Schedule is a type that provides a next runtime after a given previous runtime.
func DailyAtUTC ¶ added in v0.3.2
DailyAtUTC returns a schedule that fires every day at the given hour, minute and second in UTC.
func EveryHourAtUTC ¶ added in v1.20201204.1
EveryHourAtUTC returns a schedule that fires every hour at a given minute.
func EveryHourOnTheHour ¶
func EveryHourOnTheHour() Schedule
EveryHourOnTheHour returns a schedule that fires every 60 minutes on the 00th minute.
func ParseSchedule ¶ added in v1.20210103.1
ParseSchedule parses a cron formatted string into a schedule.
The string must be at least 5 components, whitespace separated. If the string has 5 components a 0 will be prepended for the seconds component, and a * appended for the year component. If the string has 6 components a * appended for the year component.
The components are (in short form / 5 component):
(minutes) (hours) (day of month) (month) (day of week)
The components are (in medium form / 6 component):
(seconds) (hours) (day of month) (month) (day of week)
The components are (in long form / 7 component):
(seconds) (minutes) (hours) (day of month) (month) (day of week) (year)
The full list of possible field values:
Field name Mandatory? Allowed values Allowed special characters ---------- ---------- -------------- -------------------------- Seconds No 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-6 or SUN-SAT * / , - L # Year No 1970–2099 * / , -
You can also use shorthands:
"@yearly" is equivalent to "0 0 0 1 1 * *" "@monthly" is equivalent to "0 0 0 1 * * *" "@weekly" is equivalent to "0 0 0 * * 0 *" "@daily" is equivalent to "0 0 0 * * * *" "@hourly" is equivalent to "0 0 * * * * *" "@every 500ms" is equivalent to "cron.Every(500 * time.Millisecond)"" "@immediately-then @every 500ms" is equivalent to "cron.Immediately().Then(cron.Every(500*time.Millisecond))" "@once-at 2021-06-05 13:04" is "cron.OnceAtUTC(time.Date(...))" "@never" is equivalent to an unset schedule (i.e., only on demand) to avoid defaults
func WeekdaysAtUTC ¶ added in v0.3.2
WeekdaysAtUTC returns a schedule that fires every week day at the given hour, minute and second in UTC>
func WeekendsAtUTC ¶ added in v0.3.2
WeekendsAtUTC returns a schedule that fires every weekend day at the given hour, minut and second.
type ScheduleFunc ¶ added in v1.20210701.2
ScheduleFunc is a function that implements schedule.
type ScheduleProvider ¶ added in v0.3.2
type ScheduleProvider interface {
Schedule() Schedule
}
ScheduleProvider is a type that provides a schedule for the job. If a job does not implement this method, it is treated as "OnDemand" or a job that must be triggered explicitly.
type StringSchedule ¶ added in v1.20201204.1
type StringSchedule struct { Original string Seconds []int Minutes []int Hours []int DaysOfMonth []int Months []int DaysOfWeek []int Years []int }
StringSchedule is a schedule generated from a cron string.
func (*StringSchedule) FullString ¶ added in v1.20201204.1
func (ss *StringSchedule) FullString() string
FullString returns a fully formed string representation of the schedule's components. It shows fields as expanded.
func (*StringSchedule) Next ¶ added in v1.20201204.1
func (ss *StringSchedule) Next(after time.Time) time.Time
Next implements cron.Schedule.
func (*StringSchedule) String ¶ added in v1.20201204.1
func (ss *StringSchedule) String() string
String returns the original string schedule.
type TimesSchedule ¶ added in v1.20201204.1
TimesSchedule is a schedule that only returns a certain number of schedule "Next" results after which it returns time.Time{} for the next runtime.
func Times ¶ added in v1.20201204.1
func Times(times int, schedule Schedule) *TimesSchedule
Times returns a new times schedule that returns a given next run time from a schedule only a certain number of times.
func (*TimesSchedule) Next ¶ added in v1.20201204.1
func (ts *TimesSchedule) Next(after time.Time) time.Time
Next implements cron.Schedule.
func (*TimesSchedule) String ¶ added in v1.20201204.1
func (ts *TimesSchedule) String() string
String returns a string representation of the schedul.e
type TraceFinisher ¶
TraceFinisher is a finisher for traces.
Source Files
¶
- action.go
- cancellation.go
- constants.go
- context.go
- daily_schedule.go
- default.go
- delay_schedule.go
- doc.go
- errors.go
- event.go
- immediately_then.go
- interval_schedule.go
- job_builder.go
- job_config.go
- job_interfaces.go
- job_invocation.go
- job_lifecycle.go
- job_manager.go
- job_manager_option.go
- job_parameters.go
- job_scheduler.go
- job_scheduler_option.go
- never_schedule.go
- on_the_hour_at.go
- once_at.go
- parse_schedule.go
- schedule.go
- sort.go
- times_schedule.go
- tracer.go
- util.go