gron

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2021 License: Apache-2.0 Imports: 8 Imported by: 0

README

gron Build Status GoDoc License

Another job periodic runner like crontab supporting Go1.7+

Example

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/xgfone/gron"
)

func jobRunner(name string) gron.Runner {
	return func(c context.Context, now time.Time) (result interface{}, err error) {
		fmt.Printf("Starting to run job '%s' at '%s'\n", name, now.Format(time.RFC3339Nano))
		return
	}
}

func jobResultHook(result gron.JobResult) {
	fmt.Printf("End to run job '%s', cost '%s'.\n", result.Job.Name(), result.Cost)
}

func main() {
	exe := gron.NewExecutor()
	exe.AppendResultHooks(jobResultHook) // Add the job result hook
	exe.Start()                          // Start the executor in the background goroutine.

	// Add jobs
	exe.Schedule("job1", gron.Every(time.Minute), jobRunner("job1"))
	exe.Schedule("job2", gron.MustParseWhen("@every 2m"), jobRunner("job2"))
	everyMinuteScheduler := gron.MustParseWhen("*/1 * * * *")
	exe.ScheduleJob(gron.NewJob("job3", everyMinuteScheduler, jobRunner("job3")))

	go func() {
		time.Sleep(time.Minute * 4)
		// exe.CancelJobs("job1", "job2", "job3")
		exe.Stop()
	}()

	// Wait until the executor is stopped.
	exe.Wait()
}

Documentation

Overview

Package gron supplies another job periodic runner.

Example

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/xgfone/gron"
)

func jobRunner(name string) gron.Runner {
	return func(c context.Context, now time.Time) (result interface{}, err error) {
		fmt.Printf("Starting to run job '%s' at '%s'\n", name, now.Format(time.RFC3339Nano))
		return
	}
}

func jobResultHook(result gron.JobResult) {
	fmt.Printf("End to run job '%s', cost '%s'.\n", result.Job.Name(), result.Cost)
}

func main() {
	exe := gron.NewExecutor()
	exe.AppendResultHooks(jobResultHook) // Add the job result hook
	exe.Start()                          // Start the executor in the background goroutine.

	// Add jobs
	exe.Schedule("job1", gron.Every(time.Minute), jobRunner("job1"))
	exe.Schedule("job2", gron.MustParseWhen("@every 2m"), jobRunner("job2"))
	everyMinuteScheduler := gron.MustParseWhen("*/1 * * * *")
	exe.ScheduleJob(gron.NewJob("job3", everyMinuteScheduler, jobRunner("job3")))

	go func() {
		time.Sleep(time.Minute * 4)
		// exe.CancelJobs("job1", "job2", "job3")
		exe.Stop()
	}()

	// Wait until the executor is stopped.
	exe.Wait()
}

Index

Examples

Constants

This section is empty.

Variables

CronSpecParser is the parser to parse the cron specification expression.

View Source
var DefaultExecutor = NewExecutor()

DefaultExecutor is the default global executor.

Functions

func AppendResultHooks added in v0.3.0

func AppendResultHooks(hooks ...JobResultHook)

AppendResultHooks is equal to DefaultExecutor.AppendResultHooks(hooks...).

func CancelJobs added in v0.3.0

func CancelJobs(names ...string)

CancelJobs is equal to DefaultExecutor.CancelJobs(names...).

func Schedule

func Schedule(name string, when When, runner Runner) error

Schedule is equal to DefaultExecutor.Schedule(name, when, runner).

func ScheduleJob

func ScheduleJob(job Job) error

ScheduleJob is equal to DefaultExecutor.ScheduleJob(job).

func Start added in v0.3.0

func Start()

Start is equal to DefaultExecutor.Start().

func Stop added in v0.3.0

func Stop()

Stop is equal to DefaultExecutor.Stop().

func Wait

func Wait()

Wait is equal to DefaultExecutor.Wait().

Types

type Executor

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

Executor represents a task executor.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/xgfone/gron"
)

func jobRunner(name string) gron.Runner {
	return func(c context.Context, now time.Time) (result interface{}, err error) {
		fmt.Printf("Starting to run job '%s'\n", name)
		return
	}
}

func jobResultHook(result gron.JobResult) {
	fmt.Printf("End to run job '%s'\n", result.Job.Name())
}

func main() {
	exe := gron.NewExecutor()
	exe.AppendResultHooks(jobResultHook) // Add the job result hook
	exe.Start()                          // Start the executor in the background goroutine.

	// Add jobs
	exe.Schedule("job1", gron.Every(time.Second*4), jobRunner("job1"))
	exe.Schedule("job2", gron.MustParseWhen("@every 4s"), jobRunner("job2"))
	everyMinuteScheduler := gron.MustParseWhen("*/4 * * * * *")
	exe.ScheduleJob(gron.NewJob("job3", everyMinuteScheduler, jobRunner("job3")))

	go func() {
		time.Sleep(time.Second * 10)
		// exe.CancelJobs("job1", "job2", "job3")
		exe.Stop()
	}()

	// Wait until the executor is stopped.
	exe.Wait()

	// Example Output:
	// Starting to run job 'job3'
	// End to run job 'job3'
	// Starting to run job 'job1'
	// End to run job 'job1'
	// Starting to run job 'job3'
	// End to run job 'job3'
	// Starting to run job 'job2'
	// End to run job 'job2'
	// Starting to run job 'job3'
	// End to run job 'job3'
	// Starting to run job 'job1'
	// End to run job 'job1'
	// Starting to run job 'job2'
	// End to run job 'job2'
}
Output:

func NewExecutor

func NewExecutor() *Executor

NewExecutor returns a new job executor.

func (*Executor) AppendResultHooks added in v0.3.0

func (e *Executor) AppendResultHooks(hooks ...JobResultHook)

AppendResultHooks appends the some result hooks.

func (*Executor) CancelJobs added in v0.3.0

func (e *Executor) CancelJobs(names ...string)

CancelJobs cancels the jobs by the given names.

func (*Executor) GetAllTasks

func (e *Executor) GetAllTasks() (tasks []Task)

GetAllTasks returns the tasks of all the jobs.

func (*Executor) GetTask

func (e *Executor) GetTask(name string) (task Task, ok bool)

GetTask returns the job task by the name.

func (*Executor) Run added in v0.3.0

func (e *Executor) Run()

Run starts the executor in the current goroutine, which does not return until the executor is stopped.

func (*Executor) Schedule

func (e *Executor) Schedule(name string, when When, runner Runner) error

Schedule is equal to e.ScheduleJob(NewJob(name, when, runner)).

func (*Executor) ScheduleJob

func (e *Executor) ScheduleJob(job Job) (err error)

ScheduleJob adds a job to wait to be scheduled.

func (*Executor) SetTimeout added in v0.3.0

func (e *Executor) SetTimeout(timeout time.Duration)

SetTimeout resets the timeout of all the jobs to execute the job.

func (*Executor) Start added in v0.3.0

func (e *Executor) Start()

Start starts the executor in the background goroutine.

func (*Executor) Stop added in v0.3.0

func (e *Executor) Stop()

Stop stops all the jobs in the executor.

func (*Executor) Wait

func (e *Executor) Wait()

Wait waits until the executor is stopped.

type Job

type Job interface {
	Name() string
	When() When
	Run(c context.Context, now time.Time) (result interface{}, err error)
}

Job represents a task job.

func NewJob

func NewJob(name string, when When, runner Runner) Job

NewJob returns a simple job with the runner.

type JobResult added in v0.3.0

type JobResult struct {
	Job    Job
	Next   time.Time
	Start  time.Time
	Cost   time.Duration
	Result interface{}
	Error  error
}

JobResult is the result of the job.

type JobResultHook added in v0.3.0

type JobResultHook func(JobResult)

JobResultHook is the hook to handle the result of the job task.

type Runner

type Runner func(c context.Context, now time.Time) (interface{}, error)

Runner is the runner function of the job.

type Task

type Task struct {
	Job       Job
	Prev      time.Time     // The last time to be executed
	Next      time.Time     // The next time to be executed
	Cost      time.Duration // The cost duration to execute the job last time
	IsRunning bool          // Indicate whether the job is running
}

Task represents a job task.

func GetAllTasks

func GetAllTasks() []Task

GetAllTasks is equal to DefaultExecutor.GetAllTasks().

func GetTask

func GetTask(name string) (Task, bool)

GetTask is equal to DefaultExecutor.GetTask(name).

type When

type When interface {
	// String returns the string representation.
	String() string

	// Next returns the next UTC time when the job is executed.
	//
	// If prev is ZERO, it indicates that it's the first time.
	Next(prev time.Time) (next time.Time)
}

When represents when a job is executed.

func Every

func Every(interval time.Duration) When

Every is equal to ParseWhen("@every interval").

func EveryWithDelay added in v0.3.0

func EveryWithDelay(interval, delay time.Duration) When

EveryWithDelay is the same as Every, but delay to run the job for delay duration.

func MustParseWhen

func MustParseWhen(s string) When

MustParseWhen is the same as ParseWhen, but panic if there is an error.

func ParseWhen

func ParseWhen(spec string) (When, error)

ParseWhen parses the spec to a when implementation, which uses and returns the UTC time.

spec supports CRON Expression Format, see https://en.wikipedia.org/wiki/Cron, which also supports one of several pre-defined schedules like this:

Entry                  | Description                                | Equivalent To
-----                  | -----------                                | -------------
@yearly (or @annually) | Run once a year, midnight, Jan. 1st        | 0 0 1 1 *
@monthly               | Run once a month, midnight, first of month | 0 0 1 * *
@weekly                | Run once a week, midnight between Sat/Sun  | 0 0 * * 0
@daily (or @midnight)  | Run once a day, midnight                   | 0 0 * * *
@hourly                | Run once an hour, beginning of hour        | 0 * * * *
@every Duration        | Run once every interval duration           |

Directories

Path Synopsis
Package crontab implements the function of crontab, which is ported from github.com/robfig/cron@v3.0.1.
Package crontab implements the function of crontab, which is ported from github.com/robfig/cron@v3.0.1.

Jump to

Keyboard shortcuts

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