quartz

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT Imports: 13 Imported by: 41

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")
	ErrCronParse       = errors.New("parse cron expression")
	ErrTriggerExpired  = errors.New("trigger has expired")

	ErrIllegalState     = errors.New("illegal state")
	ErrQueueEmpty       = errors.New("queue is empty")
	ErrJobNotFound      = errors.New("job not found")
	ErrJobAlreadyExists = errors.New("job already exists")
	ErrJobIsSuspended   = errors.New("job is suspended")
	ErrJobIsActive      = errors.New("job is active")
)

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 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
"0 15 10 ? * 6L"         Fire at 10:15am on the last Friday of every month
"0 15 10 ? * 6#3"        Fire at 10:15am on the third Friday of every month
"0 15 10 L * ?"          Fire at 10:15am on the last day of every month
"0 15 10 L-2 * ?"        Fire at 10:15am on the 2nd-to-last last 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.
	// Implementations should return an error wrapping ErrQueueEmpty if the
	// queue is empty.
	Pop() (ScheduledJob, error)

	// Head returns the first scheduled job without removing it from the queue.
	// Implementations should return an error wrapping ErrQueueEmpty if the
	// queue is empty.
	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 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, error)

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

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

func NewJobQueue added in v0.12.0

func NewJobQueue() JobQueue

NewJobQueue initializes and returns an empty jobQueue.

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 the provided 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, error)

	// 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(opts ...SchedulerOpt) (Scheduler, error)

NewStdScheduler returns a new StdScheduler configured using the provided functional options.

The following options are available for configuring the scheduler:

  • WithBlockingExecution()
  • WithWorkerLimit(workerLimit int)
  • WithOutdatedThreshold(outdatedThreshold time.Duration)
  • WithRetryInterval(retryInterval time.Duration)
  • WithMisfiredChan(misfiredChan chan ScheduledJob)
  • WithQueue(queue JobQueue, queueLocker sync.Locker)
  • WithLogger(logger logger.Logger)

Example usage:

scheduler, err := quartz.NewStdScheduler(
	quartz.WithOutdatedThreshold(time.Second),
	quartz.WithLogger(myLogger),
)

type SchedulerOpt added in v0.14.0

type SchedulerOpt func(*StdScheduler) error

SchedulerOpt is a functional option type used to configure an StdScheduler.

func WithBlockingExecution added in v0.14.0

func WithBlockingExecution() SchedulerOpt

WithBlockingExecution configures the scheduler to use blocking execution. In blocking execution mode, jobs are executed synchronously in the scheduler's main loop.

func WithLogger added in v0.14.0

func WithLogger(logger logger.Logger) SchedulerOpt

WithLogger configures the logger used by the scheduler for logging messages. This enables the use of a custom logger implementation that satisfies the logger.Logger interface.

func WithMisfiredChan added in v0.14.0

func WithMisfiredChan(misfiredChan chan ScheduledJob) SchedulerOpt

WithMisfiredChan configures the channel to which misfired jobs are sent. A misfired job is a job that the scheduler was unable to execute according to its trigger schedule. If a channel is provided, misfired jobs are sent to it.

func WithOutdatedThreshold added in v0.14.0

func WithOutdatedThreshold(outdatedThreshold time.Duration) SchedulerOpt

WithOutdatedThreshold configures the time duration after which a scheduled job is considered outdated.

func WithQueue added in v0.14.0

func WithQueue(queue JobQueue, queueLocker sync.Locker) SchedulerOpt

WithQueue configures the scheduler's job queue. Custom JobQueue and sync.Locker implementations can be provided to manage scheduled jobs which allows for persistent storage in distributed mode. A standard in-memory queue and a sync.Mutex are used by default.

func WithRetryInterval added in v0.14.0

func WithRetryInterval(retryInterval time.Duration) SchedulerOpt

WithRetryInterval configures the time interval the scheduler waits before retrying to determine the next execution time for a job.

func WithWorkerLimit added in v0.14.0

func WithWorkerLimit(workerLimit int) SchedulerOpt

WithWorkerLimit configures the number of worker goroutines for concurrent job execution. This option is only used when blocking execution is disabled. If blocking execution is enabled, this setting will be ignored. The workerLimit must be non-negative.

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

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

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) Reset added in v0.12.0

func (sched *StdScheduler) Reset()

Reset is called internally to recalculate the closest job timing when there is an update to the job queue by the scheduler. In cluster mode with a shared queue, it can be triggered manually to synchronize with remote changes if one of the schedulers fails.

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