quartz

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 13 Imported by: 23

Documentation

Overview

Package quartz contains core components of the scheduling library.

Index

Constants

View Source
const (
	DefaultGroup = "default"
)

Variables

View Source
var (
	ErrIllegalArgument = errors.New("illegal argument")
	ErrIllegalState    = errors.New("illegal state")
	ErrCronParse       = errors.New("parse cron expression")
	ErrJobNotFound     = errors.New("job not found")
	ErrQueueEmpty      = errors.New("queue is empty")
	ErrTriggerExpired  = errors.New("trigger has expired")
)

Errors

View Source
var Sep = "::"

Sep is the serialization delimiter; the default is a double colon.

Functions

func NowNano

func NowNano() int64

NowNano returns the current Unix time in nanoseconds.

func ValidateCronExpression added in v0.10.0

func ValidateCronExpression(expression string) error

ValidateCronExpression validates a cron expression string. A valid expression consists of the following fields:

<second> <minute> <hour> <day-of-month> <month> <day-of-week> <year>

where the <year> field is optional. See the cron expression format table in the readme file for supported special characters.

Types

type CronTrigger

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

CronTrigger implements the quartz.Trigger interface. Used to fire a Job at given moments in time, defined with Unix 'cron-like' schedule definitions.

Examples:

Expression Meaning "0 0 12 * * ?" Fire at 12pm (noon) every day "0 15 10 ? * *" Fire at 10:15am every day "0 15 10 * * ?" Fire at 10:15am every day "0 15 10 * * ? *" Fire at 10:15am every day "0 * 14 * * ?" Fire every minute starting at 2pm and ending at 2:59pm, every day "0 0/5 14 * * ?" Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day "0 0/5 14,18 * * ?" Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day "0 0-5 14 * * ?" Fire every minute starting at 2pm and ending at 2:05pm, every day "0 10,44 14 ? 3 WED" Fire at 2:10pm and at 2:44pm every Wednesday in the month of March. "0 15 10 ? * MON-FRI" Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday "0 15 10 15 * ?" Fire at 10:15am on the 15th day of every month

func NewCronTrigger

func NewCronTrigger(expression string) (*CronTrigger, error)

NewCronTrigger returns a new CronTrigger using the UTC location.

func NewCronTriggerWithLoc added in v0.4.0

func NewCronTriggerWithLoc(expression string, location *time.Location) (*CronTrigger, error)

NewCronTriggerWithLoc returns a new CronTrigger with the given time.Location.

func (*CronTrigger) Description

func (ct *CronTrigger) Description() string

Description returns the description of the cron trigger.

func (*CronTrigger) NextFireTime

func (ct *CronTrigger) NextFireTime(prev int64) (int64, error)

NextFireTime returns the next time at which the CronTrigger is scheduled to fire.

type Job

type Job interface {
	// Execute is called by a Scheduler when the Trigger associated
	// with this job fires.
	Execute(context.Context) error

	// Description returns the description of the Job.
	Description() string
}

Job represents an interface to be implemented by structs which represent a task to be performed. Some Job implementations can be found in the job package.

type JobDetail added in v0.10.0

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

JobDetail conveys the detail properties of a given Job instance.

func NewJobDetail added in v0.10.0

func NewJobDetail(job Job, jobKey *JobKey) *JobDetail

NewJobDetail creates and returns a new JobDetail.

func NewJobDetailWithOptions added in v0.10.0

func NewJobDetailWithOptions(job Job, jobKey *JobKey, opts *JobDetailOptions) *JobDetail

NewJobDetailWithOptions creates and returns a new JobDetail configured as specified.

func (*JobDetail) Job added in v0.10.0

func (jd *JobDetail) Job() Job

Job returns job.

func (*JobDetail) JobKey added in v0.10.0

func (jd *JobDetail) JobKey() *JobKey

JobKey returns jobKey.

func (*JobDetail) Options added in v0.10.0

func (jd *JobDetail) Options() *JobDetailOptions

Options returns opts.

type JobDetailOptions added in v0.10.0

type JobDetailOptions struct {
	// MaxRetries is the maximum number of retries before aborting the
	// current job execution.
	// Default: 0.
	MaxRetries int

	// RetryInterval is the fixed time interval between retry attempts.
	// Default: 1 second.
	RetryInterval time.Duration

	// Replace indicates whether the job should replace an existing job
	// with the same key.
	// Default: false.
	Replace bool

	// Suspended indicates whether the job is paused.
	// Default: false.
	Suspended bool
}

JobDetailOptions represents additional JobDetail properties.

func NewDefaultJobDetailOptions added in v0.10.0

func NewDefaultJobDetailOptions() *JobDetailOptions

NewDefaultJobDetailOptions returns a new instance of JobDetailOptions with the default values.

type JobKey added in v0.10.0

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

JobKey represents the identifier of a scheduled job. Keys are composed of both a name and group, and the name must be unique within the group. If only a name is specified then the default group name will be used.

func NewJobKey added in v0.10.0

func NewJobKey(name string) *JobKey

NewJobKey returns a new NewJobKey using the given name.

func NewJobKeyWithGroup added in v0.10.0

func NewJobKeyWithGroup(name, group string) *JobKey

NewJobKeyWithGroup returns a new NewJobKey using the given name and group.

func (*JobKey) Equals added in v0.10.0

func (jobKey *JobKey) Equals(that *JobKey) bool

Equals indicates whether some other JobKey is "equal to" this one.

func (*JobKey) Group added in v0.11.0

func (jobKey *JobKey) Group() string

Group returns the group of the JobKey.

func (*JobKey) Name added in v0.11.0

func (jobKey *JobKey) Name() string

Name returns the name of the JobKey.

func (*JobKey) String added in v0.10.0

func (jobKey *JobKey) String() string

String returns string representation of the JobKey.

type JobQueue added in v0.10.0

type JobQueue interface {
	// Push inserts a new scheduled job to the queue.
	// This method is also used by the Scheduler to reschedule existing jobs that
	// have been dequeued for execution.
	Push(job ScheduledJob) error

	// Pop removes and returns the next to run scheduled job from the queue.
	Pop() (ScheduledJob, error)

	// Head returns the first scheduled job without removing it from the queue.
	Head() (ScheduledJob, error)

	// Get returns the scheduled job with the specified key without removing it
	// from the queue.
	Get(jobKey *JobKey) (ScheduledJob, error)

	// Remove removes and returns the scheduled job with the specified key.
	Remove(jobKey *JobKey) (ScheduledJob, error)

	// ScheduledJobs returns a slice of scheduled jobs in the queue.
	// The matchers parameter acts as a filter to build the resulting list.
	// For a job to be returned in the result slice, it must satisfy all of the
	// specified matchers. Empty matchers return all scheduled jobs in the queue.
	//
	// Custom queue implementations may consider using pattern matching on the
	// specified matchers to create a predicate pushdown effect and optimize queries
	// to filter data at the data source, e.g.
	//
	//	switch m := jobMatcher.(type) {
	//	case *matcher.JobStatus:
	//		// ... WHERE status = m.Suspended
	//	case *matcher.JobGroup:
	//		if m.Operator == &matcher.StringEquals {
	//			// ... WHERE group_name = m.Pattern
	//		}
	//	}
	ScheduledJobs([]Matcher[ScheduledJob]) []ScheduledJob

	// Size returns the size of the job queue.
	Size() int

	// Clear clears the job queue.
	Clear() error
}

JobQueue represents the job queue used by the scheduler. The default jobQueue implementation uses an in-memory priority queue that orders scheduled jobs by their next execution time, when the job with the closest time being removed and returned first. An alternative implementation can be provided for customization, e.g. to support persistent storage. The implementation is required to be thread safe.

type Matcher added in v0.11.0

type Matcher[T any] interface {
	// IsMatch evaluates this matcher on the given argument.
	IsMatch(T) bool
}

Matcher represents a predicate (boolean-valued function) of one argument. Matchers can be used in various Scheduler API methods to select the entities that should be operated. Standard Matcher implementations are located in the matcher package.

type RunOnceTrigger

type RunOnceTrigger struct {
	Delay   time.Duration
	Expired bool
}

RunOnceTrigger implements the quartz.Trigger interface. This type of Trigger can only be fired once and will expire immediately.

func NewRunOnceTrigger

func NewRunOnceTrigger(delay time.Duration) *RunOnceTrigger

NewRunOnceTrigger returns a new RunOnceTrigger with the given delay time.

func (*RunOnceTrigger) Description

func (ot *RunOnceTrigger) Description() string

Description returns the description of the trigger.

func (*RunOnceTrigger) NextFireTime

func (ot *RunOnceTrigger) NextFireTime(prev int64) (int64, error)

NextFireTime returns the next time at which the RunOnceTrigger is scheduled to fire. Sets expired to true afterwards.

type ScheduledJob

type ScheduledJob interface {
	JobDetail() *JobDetail
	Trigger() Trigger
	NextRunTime() int64
}

ScheduledJob represents a scheduled Job with the Trigger associated with it and the next run epoch time.

type Scheduler

type Scheduler interface {
	// Start starts the scheduler. The scheduler will run until
	// the Stop method is called or the context is canceled. Use
	// the Wait method to block until all running jobs have completed.
	Start(context.Context)

	// IsStarted determines whether the scheduler has been started.
	IsStarted() bool

	// ScheduleJob schedules a job using a specified trigger.
	ScheduleJob(jobDetail *JobDetail, trigger Trigger) error

	// GetJobKeys returns the keys of scheduled jobs.
	// For a job key to be returned, the job must satisfy all of the
	// matchers specified.
	// Given no matchers, it returns the keys of all scheduled jobs.
	GetJobKeys(...Matcher[ScheduledJob]) []*JobKey

	// GetScheduledJob returns the scheduled job with the specified key.
	GetScheduledJob(jobKey *JobKey) (ScheduledJob, error)

	// DeleteJob removes the job with the specified key from the
	// scheduler's execution queue.
	DeleteJob(jobKey *JobKey) error

	// PauseJob suspends the job with the specified key from being
	// executed by the scheduler.
	PauseJob(jobKey *JobKey) error

	// ResumeJob restarts the suspended job with the specified key.
	ResumeJob(jobKey *JobKey) error

	// Clear removes all of the scheduled jobs.
	Clear() error

	// Wait blocks until the scheduler stops running and all jobs
	// have returned. Wait will return when the context passed to
	// it has expired. Until the context passed to start is
	// cancelled or Stop is called directly.
	Wait(context.Context)

	// Stop shutdowns the scheduler.
	Stop()
}

Scheduler represents a Job orchestrator. Schedulers are responsible for executing Jobs when their associated Triggers fire (when their scheduled time arrives).

func NewStdScheduler

func NewStdScheduler() Scheduler

NewStdScheduler returns a new StdScheduler with the default configuration.

type SimpleTrigger

type SimpleTrigger struct {
	Interval time.Duration
}

SimpleTrigger implements the quartz.Trigger interface; uses a fixed interval.

func NewSimpleTrigger

func NewSimpleTrigger(interval time.Duration) *SimpleTrigger

NewSimpleTrigger returns a new SimpleTrigger using the given interval.

func (*SimpleTrigger) Description

func (st *SimpleTrigger) Description() string

Description returns the description of the trigger.

func (*SimpleTrigger) NextFireTime

func (st *SimpleTrigger) NextFireTime(prev int64) (int64, error)

NextFireTime returns the next time at which the SimpleTrigger is scheduled to fire.

type StdScheduler

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

StdScheduler implements the quartz.Scheduler interface.

func NewStdSchedulerWithOptions added in v0.6.0

func NewStdSchedulerWithOptions(
	opts StdSchedulerOptions,
	jobQueue JobQueue,
) *StdScheduler

NewStdSchedulerWithOptions returns a new StdScheduler configured as specified. A custom JobQueue implementation can be provided to manage scheduled jobs. This can be useful when distributed mode is required, so that jobs can be stored in persistent storage. Pass in nil to use the internal in-memory implementation.

func (*StdScheduler) Clear

func (sched *StdScheduler) Clear() error

Clear removes all of the scheduled jobs.

func (*StdScheduler) DeleteJob

func (sched *StdScheduler) DeleteJob(jobKey *JobKey) error

DeleteJob removes the Job with the specified key if present.

func (*StdScheduler) GetJobKeys

func (sched *StdScheduler) GetJobKeys(matchers ...Matcher[ScheduledJob]) []*JobKey

GetJobKeys returns the keys of scheduled jobs. For a job key to be returned, the job must satisfy all of the matchers specified. Given no matchers, it returns the keys of all scheduled jobs.

func (*StdScheduler) GetScheduledJob

func (sched *StdScheduler) GetScheduledJob(jobKey *JobKey) (ScheduledJob, error)

GetScheduledJob returns the ScheduledJob with the specified key.

func (*StdScheduler) IsStarted added in v0.3.6

func (sched *StdScheduler) IsStarted() bool

IsStarted determines whether the scheduler has been started.

func (*StdScheduler) PauseJob added in v0.11.0

func (sched *StdScheduler) PauseJob(jobKey *JobKey) error

PauseJob suspends the job with the specified key from being executed by the scheduler.

func (*StdScheduler) ResumeJob added in v0.11.0

func (sched *StdScheduler) ResumeJob(jobKey *JobKey) error

ResumeJob restarts the suspended job with the specified key.

func (*StdScheduler) ScheduleJob

func (sched *StdScheduler) ScheduleJob(
	jobDetail *JobDetail,
	trigger Trigger,
) error

ScheduleJob schedules a Job using a specified Trigger.

func (*StdScheduler) Start

func (sched *StdScheduler) Start(ctx context.Context)

Start starts the StdScheduler execution loop.

func (*StdScheduler) Stop

func (sched *StdScheduler) Stop()

Stop exits the StdScheduler execution loop.

func (*StdScheduler) Wait added in v0.6.0

func (sched *StdScheduler) Wait(ctx context.Context)

Wait blocks until the scheduler shuts down.

type StdSchedulerOptions added in v0.6.0

type StdSchedulerOptions struct {
	// When true, the scheduler will run jobs synchronously, waiting
	// for each execution instance of the job to return before starting
	// the next execution. Running with this option effectively serializes
	// all job execution.
	BlockingExecution bool

	// When greater than 0, all jobs will be dispatched to a pool of
	// goroutines of WorkerLimit size to limit the total number of processes
	// usable by the scheduler. If all worker threads are in use, job
	// scheduling will wait till a job can be dispatched.
	// If BlockingExecution is set, then WorkerLimit is ignored.
	WorkerLimit int

	// When the scheduler attempts to execute a job, if the time elapsed
	// since the job's scheduled execution time is less than or equal to the
	// configured threshold, the scheduler will execute the job.
	// Otherwise, the job will be rescheduled as outdated. By default,
	// NewStdScheduler sets the threshold to 100ms.
	//
	// As a rule of thumb, your OutdatedThreshold should always be
	// greater than 0, but less than the shortest interval used by
	// your job or jobs.
	OutdatedThreshold time.Duration

	// This retry interval will be used if the scheduler fails to
	// calculate the next time to interrupt for job execution. By default,
	// the NewStdScheduler constructor sets this interval to 100
	// milliseconds. Changing the default value may be beneficial when
	// using a custom implementation of the JobQueue, where operations
	// may timeout or fail.
	RetryInterval time.Duration
}

type Trigger

type Trigger interface {
	// NextFireTime returns the next time at which the Trigger is scheduled to fire.
	NextFireTime(prev int64) (int64, error)

	// Description returns the description of the Trigger.
	Description() string
}

Trigger represents the mechanism by which Jobs are scheduled.

Jump to

Keyboard shortcuts

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