gocron

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2020 License: BSD-2-Clause Imports: 9 Imported by: 0

README

goCron: A Golang Job Scheduling Package.

CI State Go Report Card Go Doc

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.

See also these two great articles:

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

Examples:

package main

import (
	"fmt"
	"time"

	"github.com/XTao-Technology/gocron"
)

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

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

func main() {
    // defines a new scheduler that schedules and runs jobs
    s1 := gocron.NewScheduler(time.UTC)

    s1.Every(3).Seconds().Do(task)

    // scheduler starts running jobs and current thread continues to execute
    s1.StartAsync()

    // Do jobs without params
    s2 := gocron.NewScheduler(time.UTC)
    s2.Every(1).Second().Do(task)
    s2.Every(2).Seconds().Do(task)
    s2.Every(1).Minute().Do(task)
    s2.Every(2).Minutes().Do(task)
    s2.Every(1).Hour().Do(task)
    s2.Every(2).Hours().Do(task)
    s2.Every(1).Day().Do(task)
    s2.Every(2).Days().Do(task)
    s2.Every(1).Week().Do(task)
    s2.Every(2).Weeks().Do(task)
    s2.Every(1).Month(time.Now().Day()).Do(task)
    s2.Every(2).Months(15).Do(task)

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

    // Do Jobs with tags
    // initialize tag
    tag1 := []string{"tag1"}
    tag2 := []string{"tag2"}


    s2.Every(1).Week().SetTag(tag1).Do(task)
    s2.Every(1).Week().SetTag(tag2).Do(task)

    // Removing Job Based on Tag
    s2.RemoveJobByTag("tag1")

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

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

    // Begin job at a specific date/time.
    // Attention: scheduler timezone has precedence over job's timezone!
    t := time.Date(2019, time.November, 10, 15, 0, 0, 0, time.UTC)
    s2.Every(1).Hour().StartAt(t).Do(task)

    // use .StartImmediately() to run job upon scheduler start
    s2.Every(1).Hour().StartImmediately().Do(task)


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

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

    // Clear all scheduled jobs
    s2.Clear()

    // stop our first scheduler (it still exists but doesn't run anymore)
    s1.Stop()

    // executes the scheduler and blocks current thread
    s2.StartBlocking()

    // this line is never reached
}

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)

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

Jetbrains supports this project with GoLand licenses. We appreciate their support for free and open source software!

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.

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

Examples

Constants

This section is empty.

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")
	ErrNotScheduledWeekday   = errors.New("job not scheduled weekly on a weekday")
	ErrJobNotFoundWithTag    = errors.New("no jobs found with given tag")
	ErrUnsupportedTimeFormat = errors.New("the given time format is not supported")
)

Error declarations for gocron related errors

Functions

func SetLocker

func SetLocker(l Locker)

SetLocker sets a locker implementation to be used by the scheduler for locking jobs

Types

type Job

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

Job struct stores the information necessary to run a Job

func NewJob

func NewJob(interval uint64) *Job

NewJob creates a new Job with the provided interval

func (*Job) Err

func (j *Job) Err() error

Err returns an error if one ocurred while creating the Job

func (*Job) ScheduledAtTime

func (j *Job) ScheduledAtTime() string

ScheduledAtTime returns the specific time of day the Job will run at

func (*Job) ScheduledTime

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

ScheduledTime returns the time of the Job's next scheduled run

Example
package main

import (
	"fmt"
	"time"

	"github.com/XTao-Technology/gocron"
)

var task = func() {
	fmt.Println("I am a task")
}

func main() {
	s := gocron.NewScheduler(time.UTC)
	job, _ := s.Every(1).Day().At("10:30").Do(task)
	fmt.Println(job.ScheduledAtTime())
}
Output:

10:30

func (*Job) Tag

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

Tag allows you to add arbitrary labels to a Job that do not impact the functionality of the Job

func (*Job) Tags

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

Tags returns the tags attached to the Job

func (*Job) Untag

func (j *Job) Untag(t string)

Untag removes a tag from a Job

func (*Job) Weekday

func (j *Job) Weekday() (time.Weekday, error)

Weekday returns which day of the week the Job will run on and will return an error if the Job is not scheduled weekly

type Locker

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

Locker provides an interface for implementing job locking to prevent jobs from running at the same time on multiple instances of gocron

type Scheduler

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

Scheduler struct stores a list of Jobs and the location of time Scheduler Scheduler implements the sort.Interface{} for sorting Jobs, by the time of nextRun

func NewScheduler

func NewScheduler(loc *time.Location) *Scheduler

NewScheduler creates a new Scheduler

func (*Scheduler) At

func (s *Scheduler) At(t string) *Scheduler

At schedules the Job at a specific time of day in the form "HH:MM:SS" or "HH:MM"

Example
package main

import (
	"fmt"
	"time"

	"github.com/XTao-Technology/gocron"
)

var task = func() {
	fmt.Println("I am a task")
}

func main() {
	s := gocron.NewScheduler(time.UTC)
	s.Every(1).Day().At("10:30").Do(task)
	s.Every(1).Monday().At("10:30:01").Do(task)
}
Output:

func (*Scheduler) ChangeLocation

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

ChangeLocation changes the default time location

func (*Scheduler) Clear

func (s *Scheduler) Clear()

Clear clear all Jobs from this scheduler

func (*Scheduler) Day

func (s *Scheduler) Day() *Scheduler

Day sets the unit with days

func (*Scheduler) Days

func (s *Scheduler) Days() *Scheduler

Days set the unit with days

func (*Scheduler) Do

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

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

func (*Scheduler) Every

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

Every schedules a new periodic Job with interval

func (*Scheduler) Friday

func (s *Scheduler) Friday() *Scheduler

Friday sets the start day as Friday

func (*Scheduler) Hour

func (s *Scheduler) Hour() *Scheduler

Hour sets the unit with hours

func (*Scheduler) Hours

func (s *Scheduler) Hours() *Scheduler

Hours sets the unit with hours

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

Len returns the number of Jobs in the Scheduler

func (*Scheduler) Less

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

func (*Scheduler) Lock

func (s *Scheduler) Lock() *Scheduler

Lock prevents Job to run from multiple instances of gocron

func (*Scheduler) Minute

func (s *Scheduler) Minute() *Scheduler

Minute sets the unit with minutes

func (*Scheduler) Minutes

func (s *Scheduler) Minutes() *Scheduler

Minutes sets the unit with minutes

func (*Scheduler) Monday

func (s *Scheduler) Monday() *Scheduler

Monday sets the start day as Monday

func (*Scheduler) Month

func (s *Scheduler) Month(dayOfTheMonth int) *Scheduler

Month sets the unit with months

func (*Scheduler) Months

func (s *Scheduler) Months(dayOfTheMonth int) *Scheduler

Months sets the unit with months

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) RemoveByReference

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

RemoveByReference removes specific Job j by reference

func (*Scheduler) RemoveJobByTag

func (s *Scheduler) RemoveJobByTag(tag string) error

RemoveJobByTag will Remove Jobs by Tag

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) Saturday

func (s *Scheduler) Saturday() *Scheduler

Saturday sets the start day as Saturday

func (*Scheduler) Scheduled

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

Scheduled checks if specific Job j was already added

func (*Scheduler) Second

func (s *Scheduler) Second() *Scheduler

Second sets the unit with seconds

func (*Scheduler) Seconds

func (s *Scheduler) Seconds() *Scheduler

Seconds sets the unit with seconds

func (*Scheduler) SetTag

func (s *Scheduler) SetTag(t []string) *Scheduler

SetTag will add tag when creating a job

func (*Scheduler) StartAsync

func (s *Scheduler) StartAsync() chan struct{}

StartAsync starts a goroutine that runs all the pending using a second-long ticker

func (*Scheduler) StartAt

func (s *Scheduler) StartAt(t time.Time) *Scheduler

StartAt schedules the next run of the Job

func (*Scheduler) StartBlocking

func (s *Scheduler) StartBlocking()

StartBlocking starts all the pending jobs using a second-long ticker and blocks the current thread

Example
package main

import (
	"fmt"
	"time"

	"github.com/XTao-Technology/gocron"
)

var task = func() {
	fmt.Println("I am a task")
}

func main() {
	s := gocron.NewScheduler(time.UTC)
	s.Every(3).Seconds().Do(task)
	s.StartBlocking()
}
Output:

func (*Scheduler) StartImmediately

func (s *Scheduler) StartImmediately() *Scheduler

StartImmediately sets the Jobs next run as soon as the scheduler starts

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the scheduler. This is a no-op if the scheduler is already stopped .

func (*Scheduler) Sunday

func (s *Scheduler) Sunday() *Scheduler

Sunday sets the start day as Sunday

func (*Scheduler) Swap

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

Swap

func (*Scheduler) Thursday

func (s *Scheduler) Thursday() *Scheduler

Thursday sets the start day as Thursday

func (*Scheduler) Tuesday

func (s *Scheduler) Tuesday() *Scheduler

Tuesday sets the start day as Tuesday

func (*Scheduler) Wednesday

func (s *Scheduler) Wednesday() *Scheduler

Wednesday sets the start day as Wednesday

func (*Scheduler) Week

func (s *Scheduler) Week() *Scheduler

Week sets the unit with weeks

func (*Scheduler) Weekday

func (s *Scheduler) Weekday(startDay time.Weekday) *Scheduler

Weekday sets the start with a specific weekday weekday

func (*Scheduler) Weeks

func (s *Scheduler) Weeks() *Scheduler

Weeks sets the unit with weeks

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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