scheduler

package module
v0.0.0-...-f949d11 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2023 License: MIT Imports: 12 Imported by: 4

README

scheduler

scheduler provides a lightning fast job scheduling library.

The ideas and design are based on the following projects:

Features

Installing

  1. Get package:

    go get -u github.com/cnotch/scheduler
    
  2. Import it in your code:

    import "github.com/cnotch/scheduler"
    import "github.com/cnotch/scheduler/cron" // when use cron expressions directly
    

Usage

Simple example

The following example is executed for the first time at delay 1s, and then every minute(using Scheduler):

var counter int32
mj, _ := schd.PeriodFunc(time.Second, time.Minute, func() {
	atomic.AddInt32(&counter, 1)
}, nil)
// other code
mj.Cancel()
Handle panic example

The following example cancels the job when a panic occurs

schd := scheduler.New(scheduler.WithPanicHandler(func(job *scheduler.ManagedJob, r interface{}) {
    // other handle code
	// If panic occurs, cancel the job;
	// Can also not cancel, continue to execute next time
	job.Cancel()
}))

//...
var counter int32

mj, _ := s.PeriodFunc(0, time.Millisecond*10, func() {
	atomic.AddInt32(&counter, 1)
	panic("test")
}, nil)
Compsite Schedule example

In China, many holidays are rescheduled so that people can have more time to travel. Take the May Day holiday in 2020 as an example, how do we get the work schedule? Below is the time schedule that is triggered at 8:30am every working day.

type whSchedule struct {
	times []time.Time
}

func (wh whSchedule) Next(t time.Time) time.Time {
	for _, lt := range wh.times {
		if lt.After(t) {
			return lt
		}
	}
	return time.Time{}
}

func ExampleCompsite() {
	t := time.Date(2020, 4, 25, 8, 30, 0, 0, time.Local)
	mon2fri := cron.MustParse("30 8 ? * 1-5")
	// The holiday (Saturday, Sunday) was transferred to a working day
	workday := whSchedule{[]time.Time{
		t.AddDate(0, 0, 1),  // 2020-04-26 08:30
		t.AddDate(0, 0, 14), // 2020-05-09 08:30
	}}

	// The working day (Monday - Friday) is changed into a holiday
	holiday := whSchedule{[]time.Time{
		t.AddDate(0, 0, 6), // 2020-05-01 08:30
		t.AddDate(0, 0, 9), // 2020-05-04 08:30
		t.AddDate(0, 0, 10),// 2020-05-05 08:30
	}}
	workingSchedule := Union(Minus(mon2fri, holiday), workday)

	for i := 0; i < 12; i++ {
		t = workingSchedule.Next(t)
		fmt.Println(t.Format("2006-01-02 15:04:05"))
	}
	// Output:
	// 2020-04-26 08:30:00
	// 2020-04-27 08:30:00
	// 2020-04-28 08:30:00
	// 2020-04-29 08:30:00
	// 2020-04-30 08:30:00
	// 2020-05-06 08:30:00
	// 2020-05-07 08:30:00
	// 2020-05-08 08:30:00
	// 2020-05-09 08:30:00
	// 2020-05-11 08:30:00
	// 2020-05-12 08:30:00
	// 2020-05-13 08:30:00
}

Benchmarks

gorhill/cronexpr

BenchmarkParse-8   	   64550	     18287 ns/op	    5955 B/op	      79 allocs/op
BenchmarkNext-8    	  243950	      5676 ns/op	     517 B/op	      18 allocs/op

cnotch/scheduler

BenchmarkParse-8   	 2024068	       575 ns/op	     249 B/op	       3 allocs/op
BenchmarkNext-8    	  425515	      2972 ns/op	       0 B/op	       0 allocs/op

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Count

func Count() int

Count returns jobs count of the global scheduler.

func Location

func Location() *time.Location

Location returns the time zone location of the global scheduler.

func SetPanicHandler

func SetPanicHandler(panicHandler PanicHandler)

SetPanicHandler set the panic handler of the global scheduler.

Types

type Job

type Job interface {
	// Run called by the Scheduler When the Schedule associated with the Job is triggered.
	Run()
}

Job represent a 'job' to be performed.

type JobFunc

type JobFunc func()

JobFunc is an adapter to allow the use of ordinary functions as the Job interface.

func (JobFunc) Run

func (jf JobFunc) Run()

Run called by the Scheduler When the Schedule associated with the Job is triggered.

type ManagedJob

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

ManagedJob represent the job managed by the scheduler.

func After

func After(delay time.Duration, job Job, tag interface{}) (*ManagedJob, error)

After posts the job to the default Scheduler. The job will execute after specified delay only once, and then remove from the Scheduler.

func AfterFunc

func AfterFunc(delay time.Duration, f func(), tag interface{}) (*ManagedJob, error)

AfterFunc posts the function f to the default Scheduler. The function f will execute after specified delay only once, and then remove from the Scheduler.

func Cron

func Cron(cronExpr string, job Job, tag interface{}) (*ManagedJob, error)

Cron posts the job to the default Scheduler, and associate the given cron expression with it.

func CronFunc

func CronFunc(cronExpr string, f func(), tag interface{}) (*ManagedJob, error)

CronFunc posts the function f to the default Scheduler, and associate the given cron expression with it.

func Jobs

func Jobs() (jobs []*ManagedJob)

Jobs returns the scheduled jobs of the global scheduler.

func Period

func Period(initialDelay, period time.Duration, job Job, tag interface{}) (*ManagedJob, error)

Period posts the job to the default Scheduler. The job will execute the first time at the specified delay, followed by a fixed period. If the execution time of job exceeds the period, there will be multiple instances of job running at the same time.

func PeriodFunc

func PeriodFunc(initialDelay, period time.Duration, f func(), tag interface{}) (*ManagedJob, error)

PeriodFunc posts the function f to the default Scheduler. The function f will execute the first time at the specified delay, followed by a fixed period. If the execution time of f exceeds the period, there will be multiple instances of f running at the same time.

func Post

func Post(schedule Schedule, job Job, tag interface{}) (mjob *ManagedJob, err error)

Post posts the job to the default Scheduler, and associate the given schedule with it.

func PostFunc

func PostFunc(schedule Schedule, f func(), tag interface{}) (*ManagedJob, error)

PostFunc posts the function f to the default Scheduler, and associate the given schedule with it.

func (*ManagedJob) Cancel

func (mjob *ManagedJob) Cancel()

Cancel cancel the scheduled job.

func (*ManagedJob) Job

func (mjob *ManagedJob) Job() Job

Job return the executive job of the job.

func (*ManagedJob) NextTime

func (mjob *ManagedJob) NextTime() time.Time

NextTime returns the next execution time of the job.

func (*ManagedJob) PostTime

func (mjob *ManagedJob) PostTime() time.Time

PostTime returns the time the job was posted to the scheduler

func (*ManagedJob) PrevTime

func (mjob *ManagedJob) PrevTime() time.Time

PrevTime returns the prev execution time of the job.

func (*ManagedJob) Schelule

func (mjob *ManagedJob) Schelule() Schedule

Schelule returns the schedule of the job.

func (*ManagedJob) Tag

func (mjob *ManagedJob) Tag() interface{}

Tag returns the tag of the job.

type Option

type Option interface {
	// contains filtered or unexported methods
}

An Option configures a Scheduler.

func WithContext

func WithContext(ctx context.Context) Option

WithContext configures the context of the Scheduler.

func WithLocation

func WithLocation(location *time.Location) Option

WithLocation configures the location of the Scheduler.

func WithPanicHandler

func WithPanicHandler(panicHandler PanicHandler) Option

WithPanicHandler configures the panic exception handler.

type PanicHandler

type PanicHandler func(job *ManagedJob, r interface{})

PanicHandler is to handle panic caused by an asynchronous job.

type Schedule

type Schedule interface {
	// Next returns the next activation time, later than the given time.
	// Next returns 0(Time.IsZero()) to indicate job termination.
	Next(time.Time) time.Time
}

Schedule describes a job's duty cycle.

func Intersect

func Intersect(l, r Schedule) Schedule

Intersect returns the intersection of left schedule and right schedule(l ∩ r).

func Minus

func Minus(l, r Schedule) Schedule

Minus returns the new schedule that the left schedule minus the right schedule(l - r).

func Union

func Union(l, r Schedule) Schedule

Union returns the new schedule that union left schedule and right schedule(left ∪ right).

Example

ExampleUnion

t := time.Date(2020, 4, 25, 8, 30, 0, 0, time.Local)
mon2fri := cron.MustParse("30 8 ? * 1-5")
// The holiday (Saturday, Sunday) was transferred to a working day
workday := whSchedule{[]time.Time{
	t.AddDate(0, 0, 1),  // 2020-04-26 08:30
	t.AddDate(0, 0, 14), // 2020-05-09 08:30
}}

// The working day (Monday - Friday) is changed into a holiday
holiday := whSchedule{[]time.Time{
	t.AddDate(0, 0, 6),  // 2020-05-01 08:30
	t.AddDate(0, 0, 9),  // 2020-05-04 08:30
	t.AddDate(0, 0, 10), // 2020-05-05 08:30
}}
workingSchedule := Union(Minus(mon2fri, holiday), workday)

for i := 0; i < 12; i++ {
	t = workingSchedule.Next(t)
	fmt.Println(t.Format("2006-01-02 15:04:05"))
}
Output:

2020-04-26 08:30:00
2020-04-27 08:30:00
2020-04-28 08:30:00
2020-04-29 08:30:00
2020-04-30 08:30:00
2020-05-06 08:30:00
2020-05-07 08:30:00
2020-05-08 08:30:00
2020-05-09 08:30:00
2020-05-11 08:30:00
2020-05-12 08:30:00
2020-05-13 08:30:00

type ScheduleFunc

type ScheduleFunc func(time.Time) time.Time

ScheduleFunc is an adapter to allow the use of ordinary functions as the Schedule interface.

func (ScheduleFunc) Next

func (f ScheduleFunc) Next(t time.Time) time.Time

Next returns the next activation time, later than the given time.

type Scheduler

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

A Scheduler maintains a registry of Jobs. Once registered, the Scheduler is responsible for executing Jobs when their scheduled time arrives.

func New

func New(options ...Option) *Scheduler

New returns a new Scheduler instance.

func (*Scheduler) After

func (s *Scheduler) After(delay time.Duration, job Job, tag interface{}) (*ManagedJob, error)

After posts the job to the Scheduler. The job will execute after specified delay only once, and then remove from the Scheduler.

func (*Scheduler) AfterFunc

func (s *Scheduler) AfterFunc(delay time.Duration, f func(), tag interface{}) (*ManagedJob, error)

AfterFunc posts the function f to the Scheduler. The function f will execute after specified delay only once, and then remove from the Scheduler.

func (*Scheduler) Count

func (s *Scheduler) Count() int

Count returns jobs count.

func (*Scheduler) Cron

func (s *Scheduler) Cron(cronExpr string, job Job, tag interface{}) (*ManagedJob, error)

Cron posts the job to the Scheduler, and associate the given cron expression with it.

func (*Scheduler) CronFunc

func (s *Scheduler) CronFunc(cronExpr string, f func(), tag interface{}) (*ManagedJob, error)

CronFunc posts the function f to the Scheduler, and associate the given cron expression with it.

func (*Scheduler) Jobs

func (s *Scheduler) Jobs() (jobs []*ManagedJob)

Jobs returns the scheduled jobs.

func (*Scheduler) Location

func (s *Scheduler) Location() *time.Location

Location returns the time zone location of the scheduler.

func (*Scheduler) Period

func (s *Scheduler) Period(initialDelay, period time.Duration, job Job, tag interface{}) (*ManagedJob, error)

Period posts the job to the Scheduler. The job will execute the first time at the specified delay, followed by a fixed period. If the execution time of job exceeds the period, there will be multiple instances of job running at the same time.

func (*Scheduler) PeriodFunc

func (s *Scheduler) PeriodFunc(initialDelay, period time.Duration, f func(), tag interface{}) (*ManagedJob, error)

PeriodFunc posts the function f to the Scheduler. The function f will execute the first time at the specified delay, followed by a fixed period. If the execution time of f exceeds the period, there will be multiple instances of f running at the same time.

func (*Scheduler) Post

func (s *Scheduler) Post(schedule Schedule, job Job, tag interface{}) (mjob *ManagedJob, err error)

Post posts the job to the Scheduler, and associate the given schedule with it.

func (*Scheduler) PostFunc

func (s *Scheduler) PostFunc(schedule Schedule, f func(), tag interface{}) (*ManagedJob, error)

PostFunc posts the function f to the Scheduler, and associate the given schedule with it.

func (*Scheduler) SetPanicHandler

func (s *Scheduler) SetPanicHandler(panicHandler PanicHandler)

SetPanicHandler set the panic handler of the scheduler.

func (*Scheduler) Shutdown

func (s *Scheduler) Shutdown()

Shutdown shutdowns scheduler.

func (*Scheduler) ShutdownAndWait

func (s *Scheduler) ShutdownAndWait()

ShutdownAndWait shutdowns scheduler and wait for all jobs to complete.

func (*Scheduler) Terminated

func (s *Scheduler) Terminated() bool

Terminated determines that the scheduler has terminated

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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