cron

package
v1.20220411.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 17 Imported by: 5

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

View Source
const (
	DefaultTimeout               time.Duration = 0
	DefaultHistoryRestoreTimeout               = 5 * time.Second
	DefaultShutdownGracePeriod   time.Duration = 0
)

Constats and defaults

View Source
const (
	// DefaultDisabled is a default.
	DefaultDisabled = false
	// DefaultShouldSkipLoggerListeners is a default.
	DefaultShouldSkipLoggerListeners = false
	// DefaultShouldSkipLoggerOutput is a default.
	DefaultShouldSkipLoggerOutput = false
)
View Source
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"
)
View Source
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"
)
View Source
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

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 (
	// 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?

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 ConstBool added in v1.20201204.1

func ConstBool(value bool) func() bool

ConstBool returns a value provider for a constant.

func ConstDuration added in v1.20201204.1

func ConstDuration(value time.Duration) func() time.Duration

ConstDuration returns a value provider for a constant.

func ConstInt added in v1.20201204.1

func ConstInt(value int) func() int

ConstInt returns a value provider for a constant.

func ConstLabels added in v1.20201204.1

func ConstLabels(labels map[string]string) func() map[string]string

ConstLabels returns a value provider for a constant.

func FormatTime

func FormatTime(t time.Time) string

FormatTime returns a string for a time.

func IsContextCanceled added in v1.20210819.9

func IsContextCanceled(ctx context.Context) bool

IsContextCanceled check if a job is canceled

func IsJobAlreadyLoaded

func IsJobAlreadyLoaded(err error) bool

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

func IsJobAlreadyRunning added in v1.20201204.1

func IsJobAlreadyRunning(err error) bool

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

func IsJobCanceled added in v1.20210819.9

func IsJobCanceled(err error) bool

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

func IsJobNotFound added in v0.3.2

func IsJobNotFound(err error) bool

IsJobNotFound 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 Max

func Max(t1, t2 time.Time) time.Time

Max returns the maximum of two times.

func Min

func Min(t1, t2 time.Time) time.Time

Min returns the minimum of two times.

func NewEventListener

func NewEventListener(listener func(context.Context, Event)) logger.Listener

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 Now

func Now() time.Time

Now returns a new timestamp.

func SetDefault

func SetDefault(jm *JobManager)

SetDefault sets the default job manager.

func Since

func Since(t time.Time) time.Duration

Since returns the duration since another timestamp.

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 Action added in v0.3.2

type Action func(ctx context.Context) error

Action is an function that can be run as a task

type BackgroundProvider added in v1.20201204.1

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

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

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 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.

func (Event) Complete

func (e Event) Complete() bool

Complete returns if the event completed.

func (Event) Decompose added in v1.20201204.1

func (e Event) Decompose() map[string]interface{}

Decompose implements logger.JSONWritable.

func (Event) GetFlag added in v1.20201204.1

func (e Event) GetFlag() string

GetFlag implements logger.Event.

func (Event) WriteText

func (e Event) WriteText(tf logger.TextFormatter, wr io.Writer)

WriteText implements logger.TextWritable.

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

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

func (jc JobConfig) DisabledOrDefault() bool

DisabledOrDefault returns a value or a default.

func (*JobConfig) Resolve added in v1.20210103.1

func (jc *JobConfig) Resolve(ctx context.Context) error

Resolve implements configutil.Resolver.

func (JobConfig) ShutdownGracePeriodOrDefault added in v1.20201204.1

func (jc JobConfig) ShutdownGracePeriodOrDefault() time.Duration

ShutdownGracePeriodOrDefault returns a value or a default.

func (JobConfig) TimeoutOrDefault added in v1.20201204.1

func (jc JobConfig) TimeoutOrDefault() time.Duration

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 New

func New(options ...JobManagerOption) *JobManager

New returns a new job manager.

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

type JobParameters = map[string]string

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

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 Never added in v1.20210701.2

func Never() NeverSchedule

Never returns a never schedule.

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

type OnTheHourAtUTCSchedule struct {
	Minute int
	Second int
}

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

type OnceAtUTCSchedule struct {
	Time time.Time
}

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

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 EveryHourAtUTC added in v1.20201204.1

func EveryHourAtUTC(minute, second int) Schedule

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

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 added in v0.3.2

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 added in v0.3.2

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 added in v0.3.2

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 added in v1.20210701.2

type ScheduleFunc func(time.Time) time.Time

ScheduleFunc is a function that implements schedule.

func (ScheduleFunc) Next added in v1.20210701.2

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

Next 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

type TimesSchedule struct {
	sync.Mutex
	// contains filtered or unexported fields
}

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

type TraceFinisher interface {
	Finish(context.Context, error)
}

TraceFinisher is a finisher for traces.

type Tracer

type Tracer interface {
	Start(context.Context, string) (context.Context, TraceFinisher)
}

Tracer is a trace handler.

Jump to

Keyboard shortcuts

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