cron

package
v0.0.0-...-bc49051 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTimeout             time.Duration = 0
	DefaultShutdownGracePeriod time.Duration = 0
)

Constats and defaults

View Source
const (
	StringScheduleImmediately     = "@immediately"
	StringScheduleDelay           = "@delay"
	StringScheduleImmediatelyThen = "@immediately-then"
	StringScheduleEvery           = "@every"
	StringScheduleOnceAt          = "@once-at"
	StringScheduleNever           = "@never"
)

String schedule constants

View Source
const (
	StringScheduleShorthandAnnually = "@annually"
	StringScheduleShorthandYearly   = "@yearly"
	StringScheduleShorthandMonthly  = "@monthly"
	StringScheduleShorthandWeekly   = "@weekly"
	StringScheduleShorthandDaily    = "@daily"
	StringScheduleShorthandHourly   = "@hourly"
)

String schedule shorthands labels

View Source
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

View Source
var (
	// ErrJobNotLoaded is a common error.
	ErrJobNotLoaded = errors.New("job not loaded")
	// ErrJobAlreadyLoaded is a common error.
	ErrJobAlreadyLoaded = errors.New("job already loaded")
	// ErrJobCanceled is a common error.
	ErrJobCanceled = errors.New("job canceled")
	// ErrJobAlreadyRunning is a common error.
	ErrJobAlreadyRunning = errors.New("job already running")
)
View Source
var (
	// ErrCannotStart is a common error.
	ErrCannotStart = errors.New("cannot start; already started")
	// ErrCannotStop is a common error.
	ErrCannotStop = errors.New("cannot stop; already stopped")
)
View Source
var (
	ErrStringScheduleInvalid         = errors.New("cron: schedule string invalid")
	ErrStringScheduleComponents      = errors.New("cron: must have at least (5) components space delimited; ex: '0 0 * * * * *'")
	ErrStringScheduleValueOutOfRange = errors.New("cron: string schedule part out of range")
	ErrStringScheduleInvalidRange    = errors.New("cron: range (from-to) invalid")
)

Error Constants

View Source
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,
	}

	// WeekendDays 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{}
)
View Source
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 IsJobAlreadyLoaded

func IsJobAlreadyLoaded(err error) bool

IsJobAlreadyLoaded returns if the error is a job already loaded error.

func IsJobAlreadyRunning

func IsJobAlreadyRunning(err error) bool

IsJobAlreadyRunning returns if the error is a task not found error.

func IsJobCanceled

func IsJobCanceled(err error) bool

IsJobCanceled returns if the error is a task not found error.

func IsJobNotLoaded

func IsJobNotLoaded(err error) bool

IsJobNotLoaded returns if the error is a job not loaded error.

func IsWeekDay

func IsWeekDay(day time.Weekday) bool

IsWeekDay returns if the day is a monday->friday.

func IsWeekendDay

func IsWeekendDay(day time.Weekday) bool

IsWeekendDay returns if the day is a monday->friday.

func Now

func Now() time.Time

Now returns a new timestamp.

func Since

func Since(t time.Time) time.Duration

Since returns the duration since another timestamp.

func WithJobInvocation

func WithJobInvocation(ctx context.Context, ji *JobInvocation) context.Context

WithJobInvocation adds job invocation to a context.

func WithJobManager

func WithJobManager(ctx context.Context, jm *JobManager) context.Context

WithJobManager adds a job manager to a context.

func WithJobParameterValues

func WithJobParameterValues(ctx context.Context, values JobParameters) context.Context

WithJobParameterValues adds job invocation parameter values to a context.

func WithJobScheduler

func WithJobScheduler(ctx context.Context, js *JobScheduler) context.Context

WithJobScheduler adds a job scheduler to a context.

Types

type Action

type Action func(ctx context.Context) error

Action is an function that can be run as a task

type BackgroundProvider

type BackgroundProvider interface {
	Background(context.Context) context.Context
}

BackgroundProvider is a type that returns a base context based on a parent context.

type ConfigProvider

type ConfigProvider interface {
	Config() JobConfig
}

ConfigProvider is a type that returns a job config.

type DailySchedule

type DailySchedule struct {
	DayOfWeekMask uint
	TimeOfDayUTC  time.Time
}

DailySchedule is a schedule that fires every day that satisfies the DayOfWeekMask at the given TimeOfDayUTC.

func (DailySchedule) Next

func (ds DailySchedule) Next(after time.Time) time.Time

Next implements Schedule.

func (DailySchedule) String

func (ds DailySchedule) String() string

type DelaySchedule

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

DelaySchedule wraps a schedule with a delay.

func Delay

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

func (ds *DelaySchedule) Next(after time.Time) time.Time

Next implements Schedule.

func (*DelaySchedule) String

func (ds *DelaySchedule) String() string

String implements a string schedule.

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

func (i *ImmediateSchedule) Next(after time.Time) time.Time

Next implements Schedule.

func (*ImmediateSchedule) String

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

type IntervalSchedule struct {
	Every time.Duration
}

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

func (i IntervalSchedule) Next(after time.Time) time.Time

Next implements Schedule.

func (IntervalSchedule) String

func (i IntervalSchedule) String() string

String returns a string representation of the schedule.

type Job

type Job interface {
	Name() string
	Execute(context.Context) error
}

Job is an interface types can satisfy to be loaded into the JobManager.

type JobBuilder

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

func (jb *JobBuilder) Background(ctx context.Context) context.Context

Background implements BackgroundProvider.

func (*JobBuilder) Config

func (jb *JobBuilder) Config() JobConfig

Config returns the job config.

func (*JobBuilder) Execute

func (jb *JobBuilder) Execute(ctx context.Context) error

Execute runs the job action if it's set.

func (*JobBuilder) Lifecycle

func (jb *JobBuilder) Lifecycle() JobLifecycle

Lifecycle returns the job lifecycle hooks.

func (*JobBuilder) Name

func (jb *JobBuilder) Name() string

Name returns the job name.

func (*JobBuilder) Schedule

func (jb *JobBuilder) Schedule() Schedule

Schedule returns the job schedule if a provider is set.

type JobBuilderOption

type JobBuilderOption func(*JobBuilder)

JobBuilderOption is a job builder option.

func OptJobAction

func OptJobAction(action func(context.Context) error) JobBuilderOption

OptJobAction sets the job action.

func OptJobBackground

func OptJobBackground(provider func(context.Context) context.Context) JobBuilderOption

OptJobBackground sets the background provider.

func OptJobConfig

func OptJobConfig(cfg JobConfig) JobBuilderOption

OptJobConfig sets the job config.

func OptJobDisabled

func OptJobDisabled(disabled bool) JobBuilderOption

OptJobDisabled is a job builder sets the job timeout provder.

func OptJobLabels

func OptJobLabels(labels map[string]string) JobBuilderOption

OptJobLabels is a job builder sets the job labels.

func OptJobName

func OptJobName(name string) JobBuilderOption

OptJobName sets the job name.

func OptJobNamef

func OptJobNamef(format string, args ...interface{}) JobBuilderOption

OptJobNamef sets the job name by a format and args using `fmt.Sprintf`

func OptJobOnBegin

func OptJobOnBegin(handler func(context.Context)) JobBuilderOption

OptJobOnBegin sets a lifecycle hook.

func OptJobOnBroken

func OptJobOnBroken(handler func(context.Context)) JobBuilderOption

OptJobOnBroken sets a lifecycle hook.

func OptJobOnCancellation

func OptJobOnCancellation(handler func(context.Context)) JobBuilderOption

OptJobOnCancellation sets the on cancellation lifecycle hook.

func OptJobOnComplete

func OptJobOnComplete(handler func(context.Context)) JobBuilderOption

OptJobOnComplete sets a lifecycle hook.

func OptJobOnDisabled

func OptJobOnDisabled(handler func(context.Context)) JobBuilderOption

OptJobOnDisabled sets a lifecycle hook.

func OptJobOnEnabled

func OptJobOnEnabled(handler func(context.Context)) JobBuilderOption

OptJobOnEnabled sets a lifecycle hook.

func OptJobOnError

func OptJobOnError(handler func(context.Context)) JobBuilderOption

OptJobOnError sets a lifecycle hook.

func OptJobOnFixed

func OptJobOnFixed(handler func(context.Context)) JobBuilderOption

OptJobOnFixed sets a lifecycle hook.

func OptJobOnRegister

func OptJobOnRegister(handler func(context.Context) error) JobBuilderOption

OptJobOnRegister sets a lifecycle hook.

func OptJobOnRemove

func OptJobOnRemove(handler func(context.Context) error) JobBuilderOption

OptJobOnRemove sets a lifecycle hook.

func OptJobOnSuccess

func OptJobOnSuccess(handler func(context.Context)) JobBuilderOption

OptJobOnSuccess sets a lifecycle hook.

func OptJobSchedule

func OptJobSchedule(schedule Schedule) JobBuilderOption

OptJobSchedule is a job builder sets the job schedule provder.

func OptJobShutdownGracePeriod

func OptJobShutdownGracePeriod(d time.Duration) JobBuilderOption

OptJobShutdownGracePeriod is a job builder sets the job shutdown grace period provder.

func OptJobTimeout

func OptJobTimeout(d time.Duration) JobBuilderOption

OptJobTimeout is a job builder sets the job timeout provder.

type JobConfig

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) ShutdownGracePeriodOrDefault

func (jc JobConfig) ShutdownGracePeriodOrDefault() time.Duration

ShutdownGracePeriodOrDefault returns a value or a default.

func (JobConfig) TimeoutOrDefault

func (jc JobConfig) TimeoutOrDefault() time.Duration

TimeoutOrDefault returns a value or a default.

type JobInvocation

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:"-"`
	Finished chan struct{}      `json:"-"`
}

JobInvocation is metadata for a job invocation (or instance of a job running).

func GetJobInvocation

func GetJobInvocation(ctx context.Context) *JobInvocation

GetJobInvocation gets the job invocation from a given context.

func (JobInvocation) Clone

func (ji JobInvocation) Clone() *JobInvocation

Clone clones the job invocation.

func (JobInvocation) Elapsed

func (ji JobInvocation) Elapsed() time.Duration

Elapsed returns the elapsed time for the invocation.

type JobInvocationStatus

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

type JobLifecycle struct {
	// OnRegister is called when the job is loaded into the job manager.
	OnRegister func(context.Context) error
	// OnRemove is called when the job is removed from the manager
	// or the job manager is stopped.
	OnRemove 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 {
	// contains filtered or unexported fields
}

JobManager is the main orchestration and job management object.

func GetJobManager

func GetJobManager(ctx context.Context) *JobManager

GetJobManager gets a JobManager off a context.

func New

func New(opts ...Option) *JobManager

New returns a new job manager.

func (*JobManager) CancelJob

func (jm *JobManager) CancelJob(ctx context.Context, jobName string) (err error)

CancelJob cancels (sends the cancellation signal) to a running job.

func (*JobManager) Disable

func (jm *JobManager) Disable(ctx context.Context, jobNames ...string) error

Disable disables a variadic list of job names.

func (*JobManager) Enable

func (jm *JobManager) Enable(ctx context.Context, jobNames ...string) error

Enable enables a variadic list of job names.

func (*JobManager) Has

func (jm *JobManager) Has(jobName string) (hasJob bool)

Has returns if a jobName is loaded or not.

func (*JobManager) IsJobDisabled

func (jm *JobManager) IsJobDisabled(jobName string) (value bool)

IsJobDisabled returns if a job is disabled.

func (*JobManager) IsJobRunning

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, ok bool)

Job returns a job metadata by name.

func (*JobManager) Register

func (jm *JobManager) Register(ctx context.Context, jobs ...Job) error

Register adds list of jobs to the job manager and calls their "OnRegister" lifecycle handler(s).

func (*JobManager) Remove

func (jm *JobManager) Remove(ctx context.Context, jobNames ...string) (err error)

Remove removes jobs from the manager and stops them.

func (*JobManager) Restart

func (jm *JobManager) Restart(ctx context.Context) error

Restart doesn't do anything right now.

func (*JobManager) RunJob

func (jm *JobManager) RunJob(ctx context.Context, jobName string) (*JobInvocation, error)

RunJob runs a job by jobName on demand with a given context.

func (*JobManager) Start

func (jm *JobManager) Start(ctx context.Context) error

Start starts the job manager and blocks.

func (*JobManager) StartAsync

func (jm *JobManager) StartAsync(ctx context.Context) error

StartAsync starts the job manager and the loaded jobs. It does not block.

func (*JobManager) State

func (jm *JobManager) State() JobManagerState

State returns the job manager state.

func (*JobManager) Stop

func (jm *JobManager) Stop(ctx context.Context) error

Stop stops the schedule runner for a JobManager.

type JobManagerState

type JobManagerState string

JobManagerState is a job manager status.

const (
	JobManagerStateUnknown JobManagerState = "unknown"
	JobManagerStateRunning JobManagerState = "started"
	JobManagerStateStopped JobManagerState = "stopped"
)

JobManagerState values.

type JobParameters

type JobParameters = map[string]string

JobParameters is a loose association to map[string]string.

func GetJobParameterValues

func GetJobParameterValues(ctx context.Context) JobParameters

GetJobParameterValues gets parameter values from a given context.

func MergeJobParameterValues

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

type JobScheduler struct {
	Job Job
	// contains filtered or unexported fields
}

JobScheduler is a job instance.

func GetJobScheduler

func GetJobScheduler(ctx context.Context) *JobScheduler

GetJobScheduler gets a JobScheduler off a context.

func NewJobScheduler

func NewJobScheduler(jm *JobManager, job Job) *JobScheduler

NewJobScheduler returns a job scheduler for a given job.

func (*JobScheduler) CanBeScheduled

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

func (js *JobScheduler) Cancel(ctx context.Context) error

Cancel stops all running invocations.

func (*JobScheduler) Config

func (js *JobScheduler) Config() JobConfig

Config returns the job config provided by a job or an empty config.

func (*JobScheduler) Current

func (js *JobScheduler) Current() (current *JobInvocation)

Current returns the current job invocation.

func (*JobScheduler) Disable

func (js *JobScheduler) Disable(ctx context.Context)

Disable sets the job as disabled.

func (*JobScheduler) Enable

func (js *JobScheduler) Enable(ctx context.Context)

Enable sets the job as enabled.

func (*JobScheduler) IsIdle

func (js *JobScheduler) IsIdle() (isIdle bool)

IsIdle returns if the job is not currently running.

func (*JobScheduler) Labels

func (js *JobScheduler) Labels() map[string]string

Labels returns the job labels, including automatically added ones like `name`.

func (*JobScheduler) Last

func (js *JobScheduler) Last() (last *JobInvocation)

Last returns the last job invocation.

func (*JobScheduler) Lifecycle

func (js *JobScheduler) Lifecycle() JobLifecycle

Lifecycle returns job lifecycle steps or an empty set.

func (*JobScheduler) Name

func (js *JobScheduler) Name() string

Name returns the job name.

func (*JobScheduler) NotifyStarted

func (js *JobScheduler) NotifyStarted() <-chan struct{}

NotifyStarted notifies the job scheduler has started.

func (*JobScheduler) NotifyStopped

func (js *JobScheduler) NotifyStopped() <-chan struct{}

NotifyStopped notifies the job scheduler has stopped.

func (*JobScheduler) Run

func (js *JobScheduler) Run(ctx context.Context)

Run forces the job to run. This call will block.

func (*JobScheduler) RunAsync

func (js *JobScheduler) RunAsync(ctx context.Context) (*JobInvocation, error)

RunAsync starts a job invocation with a given context.

func (*JobScheduler) Start

func (js *JobScheduler) Start(ctx context.Context) error

Start starts the scheduler. This call blocks.

func (*JobScheduler) State

func (js *JobScheduler) State() JobSchedulerState

State returns the job scheduler state.

func (*JobScheduler) Stop

func (js *JobScheduler) Stop(ctx context.Context) error

Stop stops the scheduler.

type JobSchedulerEvent

type JobSchedulerEvent struct {
	Phase         string
	JobName       string
	JobInvocation string
	Parameters    JobParameters
	Err           error
	Elapsed       time.Duration
}

JobSchedulerEvent is an event.

func (JobSchedulerEvent) String

func (e JobSchedulerEvent) String() string

String implements fmt.Stringer.

type JobSchedulerState

type JobSchedulerState string

JobSchedulerState is a job manager status.

const (
	JobSchedulerStateUnknown JobSchedulerState = "unknown"
	JobSchedulerStateRunning JobSchedulerState = "started"
	JobSchedulerStateStopped JobSchedulerState = "stopped"
)

JobManagerState values.

type LifecycleProvider

type LifecycleProvider interface {
	Lifecycle() JobLifecycle
}

LifecycleProvider is a job that provides lifecycle hooks.

type Logger

type Logger interface {
	Output(int, string) error
}

Logger is a type that implements a logger.

type NeverSchedule

type NeverSchedule struct{}

NeverSchedule is a schedule that never runs.

func Never

func Never() NeverSchedule

Never returns a never schedule.

func (NeverSchedule) Next

func (ns NeverSchedule) Next(_ time.Time) time.Time

Next implements Schedule

func (NeverSchedule) String

func (ns NeverSchedule) String() string

String implements fmt.Stringer.

type OnTheHourAtSchedule

type OnTheHourAtSchedule struct {
	Minute int
	Second int
}

OnTheHourAtSchedule is a schedule that fires every hour on the given minute.

func (OnTheHourAtSchedule) Next

func (o OnTheHourAtSchedule) Next(after time.Time) time.Time

Next implements the chronometer Schedule api.

func (OnTheHourAtSchedule) String

func (o OnTheHourAtSchedule) String() string

String returns a string representation of the schedule.

type OnceAtSchedule

type OnceAtSchedule struct {
	Time time.Time
}

OnceAtSchedule is a schedule.

func OnceAt

func OnceAt(t time.Time) OnceAtSchedule

OnceAt returns a schedule that fires once at a given time. It will never fire again unless reloaded.

func (OnceAtSchedule) Next

func (oa OnceAtSchedule) Next(after time.Time) time.Time

Next returns the next runtime.

func (OnceAtSchedule) String

func (oa OnceAtSchedule) String() string

String returns a string representation of the schedule.

type Option

type Option func(*JobManager)

Option mutates a job manager.

func OptLog

func OptLog(log Logger) Option

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

func DailyAtUTC(hour, minute, second int) Schedule

DailyAtUTC returns a schedule that fires every day at the given hour, minute and second in UTC.

func EveryHourAt

func EveryHourAt(minute, second int) Schedule

EveryHourAt 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

func ParseSchedule(cronString string) (schedule Schedule, err error)

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

func WeekdaysAtUTC(hour, minute, second int) Schedule

WeekdaysAtUTC returns a schedule that fires every week day at the given hour, minute and second in UTC>

func WeekendsAtUTC

func WeekendsAtUTC(hour, minute, second int) Schedule

WeekendsAtUTC returns a schedule that fires every weekend day at the given hour, minut and second.

func WeeklyAtUTC

func WeeklyAtUTC(hour, minute, second int, days ...time.Weekday) Schedule

WeeklyAtUTC returns a schedule that fires on every of the given days at the given time by hour, minute and second in UTC.

type ScheduleFunc

type ScheduleFunc func(time.Time) time.Time

ScheduleFunc is a function that implements schedule.

func (ScheduleFunc) Next

func (sf ScheduleFunc) Next(after time.Time) time.Time

Next implements schedule.

type ScheduleProvider

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

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

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

func (ss *StringSchedule) Next(after time.Time) time.Time

Next implements cron.Schedule.

func (*StringSchedule) String

func (ss *StringSchedule) String() string

String returns the original string schedule.

Jump to

Keyboard shortcuts

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