gocron

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2020 License: BSD-2-Clause Imports: 10 Imported by: 426

README

Note from current maintainers:

A currently maintained fork of this project has been migrated to https://github.com/go-co-op/gocron

Disclaimer: we (the maintainers) tried, with no luck, to get in contact with Jason (the repository owner) in order to add new maintainers or leave the project within an organization. Unfortunately, he hasn't replied for months now (March, 2020).

So, we decided to move the project to a new repository (as stated above), in order to keep the evolution of the project coming from as many people as possible. Feel free to reach over!

goCron: A Golang Job Scheduling Package.

This package is currently looking for new maintainers (cause @jasonlvhit is in ICU). Please message @jasonlvhit if you are interested.

GgoDoc Go Report Card

goCron is a Golang job scheduling package which lets you run Go functions periodically at pre-determined interval using a simple, human-friendly syntax.

goCron is a Golang implementation of Ruby module clockwork and Python job scheduling package schedule, and personally, this package is my first Golang program, just for fun and practice.

See also this two great articles:

If you want to chat, you can find us at Slack!

Back to this package, you could just use this simple API as below, to run a cron scheduler.

package main

import (
	"fmt"
	"time"

	"github.com/jasonlvhit/gocron"
)

func task() {
	fmt.Println("I am running task.")
}

func taskWithParams(a int, b string) {
	fmt.Println(a, b)
}

func main() {
	// Do jobs without params
	gocron.Every(1).Second().Do(task)
	gocron.Every(2).Seconds().Do(task)
	gocron.Every(1).Minute().Do(task)
	gocron.Every(2).Minutes().Do(task)
	gocron.Every(1).Hour().Do(task)
	gocron.Every(2).Hours().Do(task)
	gocron.Every(1).Day().Do(task)
	gocron.Every(2).Days().Do(task)
	gocron.Every(1).Week().Do(task)
	gocron.Every(2).Weeks().Do(task)

	// Do jobs with params
	gocron.Every(1).Second().Do(taskWithParams, 1, "hello")

	// Do jobs on specific weekday
	gocron.Every(1).Monday().Do(task)
	gocron.Every(1).Thursday().Do(task)

	// Do a job at a specific time - 'hour:min:sec' - seconds optional
	gocron.Every(1).Day().At("10:30").Do(task)
	gocron.Every(1).Monday().At("18:30").Do(task)
	gocron.Every(1).Tuesday().At("18:30:59").Do(task)

	// Begin job immediately upon start
	gocron.Every(1).Hour().From(gocron.NextTick()).Do(task)

	// Begin job at a specific date/time
	t := time.Date(2019, time.November, 10, 15, 0, 0, 0, time.Local)
	gocron.Every(1).Hour().From(&t).Do(task)

	// NextRun gets the next running time
	_, time := gocron.NextRun()
	fmt.Println(time)

	// Remove a specific job
	gocron.Remove(task)

	// Clear all scheduled jobs
	gocron.Clear()

	// Start all the pending jobs
	<- gocron.Start()

	// also, you can create a new scheduler
	// to run two schedulers concurrently
	s := gocron.NewScheduler()
	s.Every(3).Seconds().Do(task)
	<- s.Start()
}

and full test cases and document will be coming soon (help is wanted! If you want to contribute, pull requests are welcome).

If you need to prevent a job from running at the same time from multiple cron instances (like running a cron app from multiple servers), you can provide a Locker implementation and lock the required jobs.

gocron.SetLocker(lockerImplementation)
gocron.Every(1).Hour().Lock().Do(task)

Once again, thanks to the great works of Ruby clockwork and Python schedule package. BSD license is used, see the file License for detail.

Looking to contribute? Try to follow these guidelines:

  • Use issues for everything
  • For a small change, just send a PR!
  • For bigger changes, please open an issue for discussion before sending a PR.
  • PRs should have: tests, documentation and examples (if it makes sense)
  • You can also contribute by:
    • Reporting issues
    • Suggesting new features or enhancements
    • Improving/fixing documentation

Have fun!

Documentation

Overview

Package gocron : A Golang Job Scheduling Package.

An in-process scheduler for periodic jobs that uses the builder pattern for configuration. Schedule lets you run Golang functions periodically at pre-determined intervals using a simple, human-friendly syntax.

Inspired by the Ruby module clockwork <https://github.com/tomykaira/clockwork> and Python package schedule <https://github.com/dbader/schedule>

See also http://adam.heroku.com/past/2010/4/13/rethinking_cron/ http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/

Copyright 2014 Jason Lyu. jasonlvhit@gmail.com . All rights reserved. Use of this source code is governed by a BSD-style . license that can be found in the LICENSE file.

Index

Constants

View Source
const MAXJOBNUM = 10000

MAXJOBNUM max number of jobs, hack it if you need.

Variables

View Source
var (
	ErrTimeFormat           = errors.New("time format error")
	ErrParamsNotAdapted     = errors.New("the number of params is not adapted")
	ErrNotAFunction         = errors.New("only functions can be schedule into the job queue")
	ErrPeriodNotSpecified   = errors.New("unspecified job period")
	ErrParameterCannotBeNil = errors.New("nil paramaters cannot be used with reflection")
)

Functions

func ChangeLoc

func ChangeLoc(newLocation *time.Location)

ChangeLoc change default the time location

func Clear

func Clear()

Clear all scheduled jobs

func NextTick

func NextTick() *time.Time

NextTick returns a pointer to a time that will run at the next tick

func Remove

func Remove(j interface{})

Remove a specific job

func RunAll

func RunAll()

RunAll run all jobs regardless if they are scheduled to run or not.

func RunAllwithDelay

func RunAllwithDelay(d int)

RunAllwithDelay run all the jobs with a delay in seconds

A delay of `delay` seconds is added between each job. This can help to distribute the system load generated by the jobs more evenly over time.

func RunPending

func RunPending()

RunPending run all jobs that are scheduled to run

Please note that it is *intended behavior that run_pending() does not run missed jobs*. For example, if you've registered a job that should run every minute and you only call run_pending() in one hour increments then your job won't be run 60 times in between but only once.

func Scheduled

func Scheduled(j interface{}) bool

Scheduled checks if specific job j was already added

func SetLocker

func SetLocker(l Locker)

SetLocker sets a locker implementation

func Start

func Start() chan bool

Start run all jobs that are scheduled to run

Types

type Job

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

Job struct keeping information about job

func Every

func Every(interval uint64) *Job

Every schedules a new periodic job running in specific interval

func Jobs

func Jobs() []*Job

Jobs returns the list of Jobs from the defaultScheduler

func NewJob

func NewJob(interval uint64) *Job

NewJob creates a new job with the time interval.

func NextRun

func NextRun() (job *Job, time time.Time)

NextRun gets the next running time

func (*Job) At

func (j *Job) At(t string) *Job

At schedules job at specific time of day

s.Every(1).Day().At("10:30:01").Do(task)
s.Every(1).Monday().At("10:30:01").Do(task)

func (*Job) Day

func (j *Job) Day() *Job

Day sets the job's unit with day, which interval is 1

func (*Job) Days

func (j *Job) Days() *Job

Days set the job's unit with days

func (*Job) Do

func (j *Job) Do(jobFun interface{}, params ...interface{}) error

Do specifies the jobFunc that should be called every time the job runs

func (*Job) DoSafely

func (j *Job) DoSafely(jobFun interface{}, params ...interface{}) error

DoSafely does the same thing as Do, but logs unexpected panics, instead of unwinding them up the chain Deprecated: DoSafely exists due to historical compatibility and will be removed soon. Use Do instead

func (*Job) Err

func (j *Job) Err() error

Err should be checked to ensure an error didn't occur creating the job

func (*Job) Friday

func (j *Job) Friday() *Job

Friday sets the job start day Friday

func (*Job) From

func (j *Job) From(t *time.Time) *Job

From schedules the next run of the job

func (*Job) GetAt

func (j *Job) GetAt() string

GetAt returns the specific time of day the job will run at

s.Every(1).Day().At("10:30").GetAt() == "10:30"

func (*Job) GetWeekday

func (j *Job) GetWeekday() time.Weekday

GetWeekday returns which day of the week the job will run on This should only be used when .Weekday(...) was called on the job.

func (*Job) Hour

func (j *Job) Hour() *Job

Hour sets the unit with hour, which interval is 1

func (*Job) Hours

func (j *Job) Hours() *Job

Hours set the unit with hours

func (*Job) Loc

func (j *Job) Loc(loc *time.Location) *Job

Loc sets the location for which to interpret "At"

s.Every(1).Day().At("10:30").Loc(time.UTC).Do(task)

func (*Job) Lock

func (j *Job) Lock() *Job

Lock prevents job to run from multiple instances of gocron

func (*Job) Minute

func (j *Job) Minute() *Job

Minute sets the unit with minute, which interval is 1

func (*Job) Minutes

func (j *Job) Minutes() *Job

Minutes set the unit with minute

func (*Job) Monday

func (j *Job) Monday() (job *Job)

Monday set the start day with Monday - s.Every(1).Monday().Do(task)

func (*Job) NextScheduledTime

func (j *Job) NextScheduledTime() time.Time

NextScheduledTime returns the time of when this job is to run next

func (*Job) Saturday

func (j *Job) Saturday() *Job

Saturday sets the job start day Saturday

func (*Job) Second

func (j *Job) Second() *Job

Second sets the unit with second

func (*Job) Seconds

func (j *Job) Seconds() *Job

Seconds set the unit with seconds

func (*Job) Sunday

func (j *Job) Sunday() *Job

Sunday sets the job start day Sunday

func (*Job) Tag

func (j *Job) Tag(t string, others ...string)

Tag allows you to add labels to a job they don't impact the functionality of the job.

func (*Job) Tags

func (j *Job) Tags() []string

Tags returns the tags attached to the job

func (*Job) Thursday

func (j *Job) Thursday() *Job

Thursday sets the job start day Thursday

func (*Job) Tuesday

func (j *Job) Tuesday() *Job

Tuesday sets the job start day Tuesday

func (*Job) Untag

func (j *Job) Untag(t string)

Untag removes a tag from a job

func (*Job) Wednesday

func (j *Job) Wednesday() *Job

Wednesday sets the job start day Wednesday

func (*Job) Week

func (j *Job) Week() *Job

Week sets the job's unit with week, which interval is 1

func (*Job) Weekday

func (j *Job) Weekday(startDay time.Weekday) *Job

Weekday start job on specific Weekday

func (*Job) Weeks

func (j *Job) Weeks() *Job

Weeks sets the units as weeks

type Locker

type Locker interface {
	Lock(key string) (bool, error)
	Unlock(key string) error
}

Locker provides a method to lock jobs from running at the same time on multiple instances of gocron. You can provide any locker implementation you wish.

type Scheduler

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

Scheduler struct, the only data member is the list of jobs. - implements the sort.Interface{} for sorting jobs, by the time nextRun

func NewScheduler

func NewScheduler() *Scheduler

NewScheduler creates a new scheduler

func (*Scheduler) ChangeLoc

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

ChangeLoc changes the default time location

func (*Scheduler) Clear

func (s *Scheduler) Clear()

Clear delete all scheduled jobs

func (*Scheduler) Every

func (s *Scheduler) Every(interval uint64) *Job

Every schedule a new periodic job with interval

func (*Scheduler) Jobs

func (s *Scheduler) Jobs() []*Job

Jobs returns the list of Jobs from the Scheduler

func (*Scheduler) Len

func (s *Scheduler) Len() int

func (*Scheduler) Less

func (s *Scheduler) Less(i, j int) bool

func (*Scheduler) NextRun

func (s *Scheduler) NextRun() (*Job, time.Time)

NextRun datetime when the next job should run.

func (*Scheduler) Remove

func (s *Scheduler) Remove(j interface{})

Remove specific job j by function

func (*Scheduler) RemoveByRef

func (s *Scheduler) RemoveByRef(j *Job)

RemoveByRef removes specific job j by reference

func (*Scheduler) RunAll

func (s *Scheduler) RunAll()

RunAll run all jobs regardless if they are scheduled to run or not

func (*Scheduler) RunAllwithDelay

func (s *Scheduler) RunAllwithDelay(d int)

RunAllwithDelay runs all jobs with delay seconds

func (*Scheduler) RunPending

func (s *Scheduler) RunPending()

RunPending runs all the jobs that are scheduled to run.

func (*Scheduler) Scheduled

func (s *Scheduler) Scheduled(j interface{}) bool

Scheduled checks if specific job j was already added

func (*Scheduler) Start

func (s *Scheduler) Start() chan bool

Start all the pending jobs Add seconds ticker

func (*Scheduler) Swap

func (s *Scheduler) Swap(i, j int)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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