chrono

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 10 Imported by: 4

README

Chrono Logo

Chrono

Go Report Card CircleCI codecov

Chrono is a scheduler library that lets you run your tasks and code periodically. It provides different scheduling functionalities to make it easier to create a scheduling task.

Scheduling a One-Shot Task

The Schedule method helps us schedule the task to run once at the specified time. In the following example, the task will first be executed 1 second after the current time. WithTime option is used to specify the execution time.

taskScheduler := chrono.NewDefaultTaskScheduler()
now := time.Now()
startTime := now.Add(time.Second * 1)

task, err := taskScheduler.Schedule(func(ctx context.Context) {
	log.Print("One-Shot Task")
}, chrono.WithTime(startTime))

if err == nil {
	log.Print("Task has been scheduled successfully.")
}

Also, WithStartTime option can be used to specify the execution time. But It's deprecated.

taskScheduler := chrono.NewDefaultTaskScheduler()

task, err := taskScheduler.Schedule(func(ctx context.Context) {
	log.Print("One-Shot Task")
}, chrono.WithStartTime(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()+1))

if err == nil {
	log.Print("Task has been scheduled successfully.")
}

Scheduling a Task with Fixed Delay

Let's schedule a task to run with a fixed delay between the finish time of the last execution of the task and the start time of the next execution of the task. The fixed delay counts the delay after the completion of the last execution.

taskScheduler := chrono.NewDefaultTaskScheduler()

task, err := taskScheduler.ScheduleWithFixedDelay(func(ctx context.Context) {
	log.Print("Fixed Delay Task")
	time.Sleep(3 * time.Second)
}, 5 * time.Second)

if err == nil {
	log.Print("Task has been scheduled successfully.")
}

Since the task itself takes 3 seconds to complete and we have specified a delay of 5 seconds between the finish time of the last execution of the task and the start time of the next execution of the task, there will be a delay of 8 seconds between each execution.

WithStartTime and WithLocation options can be combined with this.

Schedule Task at a Fixed Rate

Let's schedule a task to run at a fixed rate of seconds.

taskScheduler := chrono.NewDefaultTaskScheduler()

task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
	log.Print("Fixed Rate of 5 seconds")
}, 5 * time.Second)

if err == nil {
	log.Print("Task has been scheduled successfully.")
}

The next task will run always after 5 seconds no matter the status of the previous task, which may be still running. So even if the previous task isn't done, the next task will run. We can also use the WithStartTime option to specify the desired first execution time of the task.

now := time.Now()

task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
	log.Print("Fixed Rate of 5 seconds")
}, 5 * time.Second, chrono.WithStartTime(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second() + 2))

When we use this option, the task will run at the specified execution time and subsequently with the given period. In the above example, the task will first be executed 2 seconds after the current time.

We can also combine this option with WithLocation based on our requirements.

now := time.Now()

task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
	log.Print("Fixed Rate of 5 seconds")
}, 5 * time.Second, chrono.WithStartTime(now.Year(), now.Month(), now.Day(), 18, 45, 0),
chrono.WithLocation("America/New_York"))

In the above example, the task will first be executed at 18:45 of the current date in America/New York time. If the start time is in the past, the task will be executed immediately.

Scheduling a Task using Cron Expression

Sometimes Fixed Rate and Fixed Delay can not fulfill your needs, and we need the flexibility of cron expressions to schedule the execution of your tasks. With the help of the provided ScheduleWithCron method, we can schedule a task based on a cron expression.

taskScheduler := chrono.NewDefaultTaskScheduler()

task, err := taskScheduler.ScheduleWithCron(func(ctx context.Context) {
	log.Print("Scheduled Task With Cron")
}, "0 45 18 10 * *")

if err == nil {
	log.Print("Task has been scheduled")
}

In this case, we're scheduling a task to be executed at 18:45 on the 10th day of every month

By default, the local time is used for the cron expression. However, we can use the WithLocation option to change this.

task, err := taskScheduler.ScheduleWithCron(func(ctx context.Context) {
	log.Print("Scheduled Task With Cron")
}, "0 45 18 10 * *", chrono.WithLocation("America/New_York"))

In the above example, Task will be scheduled to be executed at 18:45 on the 10th day of every month in America/New York time.

WithStartTimeoption cannot be used with ScheduleWithCron.

Canceling a Scheduled Task

Schedule methods return an instance of type ScheduledTask, which allows us to cancel a task or to check if the task is canceled. The Cancel method cancels the scheduled task but running tasks won't be interrupted.

taskScheduler := chrono.NewDefaultTaskScheduler()

task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
	log.Print("Fixed Rate of 5 seconds")
}, 5 * time.Second)

/* ... */
	
task.Cancel()

Shutting Down a Scheduler

The Shutdown() method doesn't cause immediate shut down of the Scheduler and returns a channel. It will make the Scheduler stop accepting new tasks and shut down after all running tasks finish their current work.

taskScheduler := chrono.NewDefaultTaskScheduler()

/* ... */

shutdownChannel := taskScheduler.Shutdown()
<- shutdownChannel
	
/* after all running task finished their works */

Stargazers

Forkers

License

Chrono is released under MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CronExpression

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

func ParseCronExpression

func ParseCronExpression(expression string) (*CronExpression, error)

func (*CronExpression) NextTime

func (expression *CronExpression) NextTime(t time.Time) time.Time

type CronTrigger

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

func CreateCronTrigger

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

func (*CronTrigger) NextExecutionTime

func (trigger *CronTrigger) NextExecutionTime(ctx TriggerContext) time.Time

type Option

type Option func(task *SchedulerTask) error

func WithLocation

func WithLocation(location string) Option

func WithStartTime deprecated

func WithStartTime(year int, month time.Month, day, hour, min, sec int) Option

Deprecated: Use WithTime instead.

func WithTime

func WithTime(t time.Time) Option

type ScheduledRunnableTask

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

func CreateScheduledRunnableTask

func CreateScheduledRunnableTask(id int, task Task, triggerTime time.Time, period time.Duration, fixedRate bool) (*ScheduledRunnableTask, error)

func (*ScheduledRunnableTask) Cancel

func (scheduledRunnableTask *ScheduledRunnableTask) Cancel()

func (*ScheduledRunnableTask) IsCancelled

func (scheduledRunnableTask *ScheduledRunnableTask) IsCancelled() bool

type ScheduledTask

type ScheduledTask interface {
	Cancel()
	IsCancelled() bool
}

type ScheduledTaskQueue

type ScheduledTaskQueue []*ScheduledRunnableTask

func (ScheduledTaskQueue) Len

func (queue ScheduledTaskQueue) Len() int

func (ScheduledTaskQueue) Less

func (queue ScheduledTaskQueue) Less(i, j int) bool

func (ScheduledTaskQueue) SorByTriggerTime

func (queue ScheduledTaskQueue) SorByTriggerTime()

func (ScheduledTaskQueue) Swap

func (queue ScheduledTaskQueue) Swap(i, j int)

type SchedulerTask

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

func CreateSchedulerTask

func CreateSchedulerTask(task Task, options ...Option) (*SchedulerTask, error)

func (*SchedulerTask) GetInitialDelay

func (task *SchedulerTask) GetInitialDelay() time.Duration

type SimpleTaskExecutor

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

func NewSimpleTaskExecutor

func NewSimpleTaskExecutor(runner TaskRunner) *SimpleTaskExecutor

func (*SimpleTaskExecutor) IsShutdown

func (executor *SimpleTaskExecutor) IsShutdown() bool

func (*SimpleTaskExecutor) Schedule

func (executor *SimpleTaskExecutor) Schedule(task Task, delay time.Duration) (ScheduledTask, error)

func (*SimpleTaskExecutor) ScheduleAtFixedRate

func (executor *SimpleTaskExecutor) ScheduleAtFixedRate(task Task, initialDelay time.Duration, period time.Duration) (ScheduledTask, error)

func (*SimpleTaskExecutor) ScheduleWithFixedDelay

func (executor *SimpleTaskExecutor) ScheduleWithFixedDelay(task Task, initialDelay time.Duration, delay time.Duration) (ScheduledTask, error)

func (*SimpleTaskExecutor) Shutdown

func (executor *SimpleTaskExecutor) Shutdown() chan bool

type SimpleTaskRunner

type SimpleTaskRunner struct {
}

func NewSimpleTaskRunner

func NewSimpleTaskRunner() *SimpleTaskRunner

func (*SimpleTaskRunner) Run

func (runner *SimpleTaskRunner) Run(task Task)

type SimpleTaskScheduler

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

func NewSimpleTaskScheduler

func NewSimpleTaskScheduler(executor TaskExecutor) *SimpleTaskScheduler

func (*SimpleTaskScheduler) IsShutdown

func (scheduler *SimpleTaskScheduler) IsShutdown() bool

func (*SimpleTaskScheduler) Schedule

func (scheduler *SimpleTaskScheduler) Schedule(task Task, options ...Option) (ScheduledTask, error)

func (*SimpleTaskScheduler) ScheduleAtFixedRate

func (scheduler *SimpleTaskScheduler) ScheduleAtFixedRate(task Task, period time.Duration, options ...Option) (ScheduledTask, error)

func (*SimpleTaskScheduler) ScheduleWithCron

func (scheduler *SimpleTaskScheduler) ScheduleWithCron(task Task, expression string, options ...Option) (ScheduledTask, error)

func (*SimpleTaskScheduler) ScheduleWithFixedDelay

func (scheduler *SimpleTaskScheduler) ScheduleWithFixedDelay(task Task, delay time.Duration, options ...Option) (ScheduledTask, error)

func (*SimpleTaskScheduler) Shutdown

func (scheduler *SimpleTaskScheduler) Shutdown() chan bool

type SimpleTriggerContext

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

func NewSimpleTriggerContext

func NewSimpleTriggerContext() *SimpleTriggerContext

func (*SimpleTriggerContext) LastCompletionTime

func (ctx *SimpleTriggerContext) LastCompletionTime() time.Time

func (*SimpleTriggerContext) LastExecutionTime

func (ctx *SimpleTriggerContext) LastExecutionTime() time.Time

func (*SimpleTriggerContext) LastTriggeredExecutionTime

func (ctx *SimpleTriggerContext) LastTriggeredExecutionTime() time.Time

func (*SimpleTriggerContext) Update

func (ctx *SimpleTriggerContext) Update(lastCompletionTime time.Time, lastExecutionTime time.Time, lastTriggeredExecutionTime time.Time)

type Task

type Task func(ctx context.Context)

type TaskExecutor

type TaskExecutor interface {
	Schedule(task Task, delay time.Duration) (ScheduledTask, error)
	ScheduleWithFixedDelay(task Task, initialDelay time.Duration, delay time.Duration) (ScheduledTask, error)
	ScheduleAtFixedRate(task Task, initialDelay time.Duration, period time.Duration) (ScheduledTask, error)
	IsShutdown() bool
	Shutdown() chan bool
}

func NewDefaultTaskExecutor

func NewDefaultTaskExecutor() TaskExecutor

type TaskRunner

type TaskRunner interface {
	Run(task Task)
}

func NewDefaultTaskRunner

func NewDefaultTaskRunner() TaskRunner

type TaskScheduler

type TaskScheduler interface {
	Schedule(task Task, options ...Option) (ScheduledTask, error)
	ScheduleWithCron(task Task, expression string, options ...Option) (ScheduledTask, error)
	ScheduleWithFixedDelay(task Task, delay time.Duration, options ...Option) (ScheduledTask, error)
	ScheduleAtFixedRate(task Task, period time.Duration, options ...Option) (ScheduledTask, error)
	IsShutdown() bool
	Shutdown() chan bool
}

func NewDefaultTaskScheduler

func NewDefaultTaskScheduler() TaskScheduler

type Trigger

type Trigger interface {
	NextExecutionTime(ctx TriggerContext) time.Time
}

type TriggerContext

type TriggerContext interface {
	LastCompletionTime() time.Time
	LastExecutionTime() time.Time
	LastTriggeredExecutionTime() time.Time
}

type TriggerTask

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

func CreateTriggerTask

func CreateTriggerTask(task Task, executor TaskExecutor, trigger Trigger) (*TriggerTask, error)

func (*TriggerTask) Cancel

func (task *TriggerTask) Cancel()

func (*TriggerTask) IsCancelled

func (task *TriggerTask) IsCancelled() bool

func (*TriggerTask) Run

func (task *TriggerTask) Run(ctx context.Context)

func (*TriggerTask) Schedule

func (task *TriggerTask) Schedule() (ScheduledTask, error)

Jump to

Keyboard shortcuts

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