a cron library for go

GoDoc Build Status

cron

Cron V3 has been released!

To download the specific tagged release, run:

go get github.com/robfig/cron/[email protected]

Import it in your program as:

import "github.com/robfig/cron/v3"

It requires Go 1.11 or later due to usage of Go Modules.

Refer to the documentation here: http://godoc.org/github.com/robfig/cron

The rest of this document describes the the advances in v3 and a list of breaking changes for users that wish to upgrade from an earlier version.

Upgrading to v3 (June 2019)

cron v3 is a major upgrade to the library that addresses all outstanding bugs, feature requests, and rough edges. It is based on a merge of master which contains various fixes to issues found over the years and the v2 branch which contains some backwards-incompatible features like the ability to remove cron jobs. In addition, v3 adds support for Go Modules, cleans up rough edges like the timezone support, and fixes a number of bugs.

New features:

  • Support for Go modules. Callers must now import this library as github.com/robfig/cron/v3, instead of gopkg.in/...

  • Fixed bugs:

    • 0f01e6b parser: fix combining of Dow and Dom (#70)
    • dbf3220 adjust times when rolling the clock forward to handle non-existent midnight (#157)
    • eeecf15 spec_test.go: ensure an error is returned on 0 increment (#144)
    • 70971dc cron.Entries(): update request for snapshot to include a reply channel (#97)
    • 1cba5e6 cron: fix: removing a job causes the next scheduled job to run too late (#206)
  • Standard cron spec parsing by default (first field is "minute"), with an easy way to opt into the seconds field (quartz-compatible). Although, note that the year field (optional in Quartz) is not supported.

  • Extensible, key/value logging via an interface that complies with the https://github.com/go-logr/logr project.

  • The new Chain & JobWrapper types allow you to install "interceptors" to add cross-cutting behavior like the following:

    • Recover any panics from jobs
    • Delay a job's execution if the previous run hasn't completed yet
    • Skip a job's execution if the previous run hasn't completed yet
    • Log each job's invocations
    • Notification when jobs are completed

It is backwards incompatible with both v1 and v2. These updates are required:

  • The v1 branch accepted an optional seconds field at the beginning of the cron spec. This is non-standard and has led to a lot of confusion. The new default parser conforms to the standard as described by the Cron wikipedia page.

    UPDATING: To retain the old behavior, construct your Cron with a custom parser:

// Seconds field, required
cron.New(cron.WithSeconds())

// Seconds field, optional
cron.New(cron.WithParser(cron.NewParser(
	cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)))
  • The Cron type now accepts functional options on construction rather than the previous ad-hoc behavior modification mechanisms (setting a field, calling a setter).

    UPDATING: Code that sets Cron.ErrorLogger or calls Cron.SetLocation must be updated to provide those values on construction.

  • CRON_TZ is now the recommended way to specify the timezone of a single schedule, which is sanctioned by the specification. The legacy "TZ=" prefix will continue to be supported since it is unambiguous and easy to do so.

    UPDATING: No update is required.

  • By default, cron will no longer recover panics in jobs that it runs. Recovering can be surprising (see issue #192) and seems to be at odds with typical behavior of libraries. Relatedly, the cron.WithPanicLogger option has been removed to accommodate the more general JobWrapper type.

    UPDATING: To opt into panic recovery and configure the panic logger:

cron.New(cron.WithChain(
  cron.Recover(logger),  // or use cron.DefaultLogger
))
  • In adding support for https://github.com/go-logr/logr, cron.WithVerboseLogger was removed, since it is duplicative with the leveled logging.

    UPDATING: Callers should use WithLogger and specify a logger that does not discard Info logs. For convenience, one is provided that wraps *log.Logger:

cron.New(
  cron.WithLogger(cron.VerbosePrintfLogger(logger)))

Background - Cron spec format

There are two cron spec formats in common usage:

The original version of this package included an optional "seconds" field, which made it incompatible with both of these formats. Now, the "standard" format is the default format accepted, and the Quartz format is opt-in.

Owner
Comments
  • Please Tell Me Why

    Please Tell Me Why

    I am very confused about that why I go get this pkg in my ci,the branch which be download is v3 branch not the master,my cronjob works did't work for 3 days,the most important thing is i don't know why.so could you please give me the reason about that,why!!!!!!!

  • Added RemoveFunc, PauseFunc and ResumeFunc

    Added RemoveFunc, PauseFunc and ResumeFunc

    With some test code:

    package main
    
    import (
        "fmt"
        "cron"
        "time"
    )
    
    func main() {
        c := cron.New()
        j1, _ := c.AddFunc("* * * * * *", func() { fmt.Println("1") })
        j2, _ := c.AddFunc("* * * * * *", func() { fmt.Println("2") })
        j3, _ := c.AddFunc("* * * * * *", func() { fmt.Println("3") })
        j4, _ := c.AddFunc("* * * * * *", func() { fmt.Println("4") })
        fmt.Println(j1, j2, j3, j4)
        c.RemoveFunc(j2)
        fmt.Println("j2 removed")
    
        c.Start()
    
        time.Sleep(time.Second * 5)
        c.RemoveFunc(j1)
        fmt.Println("j1 removed")
    
        time.Sleep(time.Second * 5)
        c.PauseFunc(j4)
        fmt.Println("j4 paused")
    
        time.Sleep(time.Second * 5)
        c.ResumeFunc(j4)
        fmt.Println("j4 resumed")
        select {}
    }
    

    And the output of the code above:

    1 2 3 4
    j2 removed
    1
    3
    4
    1
    3
    4
    1
    3
    4
    1
    3
    4
    1
    3
    4
    j1 removed
    3
    4
    3
    4
    3
    4
    3
    4
    3
    4
    j4 paused
    3
    3
    3
    3
    3
    j4 resumed
    3
    4
    3
    4
    3
    4
    3
    4
    3
    4
    

    I'm sorry I don't know how to exclude the .gitignore from the pull request, please just ignore it.

  • A small bug when using c.AddFunc after c.Start

    A small bug when using c.AddFunc after c.Start

    when using

    c:=cron.New()
    c.Start()
    time.Sleep(5*time.Second)
    c.AddFunc("* * * * * *",myfunc)
    

    the myfunc is

    func myfunc(){
    fmt.Println(time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05"))
    

    the output is:(current time is 15:16:07)

    2015-11-23 15:16:07  <- first in sleep 5
    2015-11-23 15:16:07  <- 2nd in sleep 5
    2015-11-23 15:16:07  <- 3rd in sleep 5
    2015-11-23 15:16:07  <- 4th in sleep 5
    2015-11-23 15:16:07  <- 5th in sleep 5
    2015-11-23 15:16:07  <- truely the first second
    2015-11-23 15:16:08  <- truely the second second
    2015-11-23 15:16:09  <- truely the third second
    

    However,modify cron.go from

    // Run the scheduler.. this is private just due to the need to synchronize
    // access to the 'running' state variable.
    func (c *Cron) Run() {
        // Figure out the next activation times for each entry.
        now := time.Now().Local()
        for _, entry := range c.entries {
            entry.Next = entry.Schedule.Next(now)
        }
    
        for {
    
            // Determine the next entry to run.
            sort.Sort(byTime(c.entries))
    

    To

    // Run the scheduler.. this is private just due to the need to synchronize
    // access to the 'running' state variable.
    func (c *Cron) Run() {
        // Figure out the next activation times for each entry.
    -   now := time.Now().Local()                                 <--------------assigned 'new' before the for loop
    -   for _, entry := range c.entries {                      
    -       entry.Next = entry.Schedule.Next(now)
    -   }                                                                     
    
        for {
    +       now := time.Now().Local()                     
    +       for _, entry := range c.entries {              
    +           entry.Next = entry.Schedule.Next(now) 
    +       }                                                                      
    
            // Determine the next entry to run.
            sort.Sort(byTime(c.entries))
    

    may solve this problem.

  • Addition of some popular features

    Addition of some popular features

    1. Seconds field is now optional and Dow field is mandatory to support standard GNU/Linux crontab format.

    2. An optional TZ= clause (ex : TZ=Europe/London) in the beginning of cron spec to support specification of cron times in that location rather than in the local timezone

    Sample usage : c := cron.New() c.AddFunc("TZ=Europe/London 07 21 * * *", func() { fmt.Println("Runs at 21:07 London time") }, "London test") c.Start()

    1. Added a function NextNTimes for Entry struct which returns next (upto) N activation times.

    2. Added DST support and test cases from github.com/lukescott/cron feature-dst branch

    3. Added safe Remove() and its test cases.

  • Panic if stop is called before start

    Panic if stop is called before start

    This was obviously an error on my part, but discovered that calling Stop without calling Start will block since nothing is receiving c.stop <- struct{}{}. This is definitely a programmer error, I suggest panicking if the cron is not running.

    // Stop the cron scheduler.
    func (c *Cron) Stop() {
        if !c.running {
            panic("cron: not running")
        }
        c.stop <- struct{}{}
        c.running = false
    }
    
  • import

    import "github.com/robfig/cron/v3" failed

    go: downloading github.com/robfig/cron/v3 v3.0.0 go: downloading github.com/robfig/cron v1.2.0 verifying github.com/robfig/cron/[email protected]: github.com/robfig/cron/[email protected]: Get https://sum.golang.org/lookup/github.com/robfig/cron/[email protected]: dial tcp 172.217.24.17:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

  • bug if add many cron at the same time

    bug if add many cron at the same time

    08:28:31.667 [trace] entity.go:106 | ##########################1, 1=>[1681,ls /] start run########################## 08:28:31.667 [trace] entity.go:106 | ##########################2, 2=>[1681,ls /] start run########################## 08:28:31.667 [trace] entity.go:106 | ##########################3, 3=>[1681,ls /] start run########################## 08:28:31.674 [trace] entity.go:106 | ##########################4, 4=>[1681,ls /] start run########################## 08:28:31.675 [trace] entity.go:106 | ##########################5, 5=>[1681,ls /] start run########################## 08:28:31.688 [trace] entity.go:106 | ##########################6, 6=>[1681,ls /] start run########################## 08:28:31.701 [trace] entity.go:114 | ##########################1, 1=>[1681,ls /] run end########################## 08:28:31.701 [trace] entity.go:114 | ##########################2, 2=>[1681,ls /] run end########################## 08:28:31.703 [trace] entity.go:114 | ##########################4, 4=>[1681,ls /] run end########################## 08:28:31.710 [trace] entity.go:114 | ##########################6, 6=>[1681,ls /] run end########################## 08:28:31.721 [trace] entity.go:114 | ##########################3, 3=>[1681,ls /] run end##########################

    cron set: data := make(url.Values) data.Add("cron_set", "*/1 * * * * *") data.Add("command", "ls /") data.Add("remark", "") data.Add("stop", "0") data.Add("start_time", "0") data.Add("end_time", "0") data.Add("is_mutex", "0")

    try to add 4 at the same time, 1681 cron is run many times at one second~

  • Using panic is not a proper way to handle errors.  This assumes that the...

    Using panic is not a proper way to handle errors. This assumes that the...

    ... developer is only ever evaluating static cron specs that aren't configured dynamically. If I wanted to utilize the Parse function in this library, and manage crons through some type of configuration interface, I would have no way to recover from parsing an improperly-formatted spec, other than deferred recover. There is a reason we don't see this practice inside the stdlib. Using errors allows me to recover from that scenario with ease.

  • not working

    not working

    // "github.com/robfig/cron/v3"

    func main() {
      c := cron.New()
      c.AddFunc("* * * * * *", func() {
        fmt.Println("working")
      })
      c.Start()
      
      select {}
    }
    

    use the latest version v3.0.1 and 3.0.0 is also not working, my useage was wrong?

  • Cron schedule for sunday is not working

    Cron schedule for sunday is not working

    Usage: I'm using package "github.com/robfig/cron/v3" to validate a cron schedule string.

    Problem: When I give input as "0 0 * * 0" (for weekly) it returns with error saying invalid schedule. As per your document, v3 supports the standards as per cron wiki page.

    This cron schedule was working fine few days ago but has started giving error recently.

    Expected outcome: The string should be considered as valid and the code should proceed.

  • Stop a not running cron block program

    Stop a not running cron block program

    Hello, I think that when Stop() is called on a not running cron, it block the program. Is there a when to know if cron is started ? running is private.

  • When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time? What can be done to ensure that the cron task is only executed once?

    When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time? What can be done to ensure that the cron task is only executed once?

    Hi! When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time? What can be done to ensure that the cron task is only executed once?

  • Add support for using mock clock in cron

    Add support for using mock clock in cron

    This PR uses https://github.com/benbjohnson/clock to mock the time. Adding support for using mock clock with cron will be helpful to write test cases and verify cron behaviour.

    Similar to this PR https://github.com/robfig/cron/pull/327 but uses a more up to date mock clock

    PR also contains fix for flaky unit tests on windows and minor linting fixes

  • Feature request: remove a job from within the job function

    Feature request: remove a job from within the job function

    I would like to be able to remove a job from within the job itself.

    A workaround is welcome too :)

    If you have an idea on how to implement, I would love to make the PR myself if needed.

    Thank you for this amazing package!

  • what is the starbit used for?

    what is the starbit used for?

    First of all, thans for your great cron job. I read dayMatches code in spec.go but did not figure out why you check starBit before return result. Why use || operation when both starBit of dom and dow is 0. I think we always need use && to get result. Could youhelp to explain some details of this? Thanks in advance :)

    // dayMatches returns true if the schedule's day-of-week and day-of-month
    // restrictions are satisfied by the given time.
    func dayMatches(s *SpecSchedule, t time.Time) bool {
    	var (
    		domMatch bool = 1<<uint(t.Day())&s.Dom > 0
    		dowMatch bool = 1<<uint(t.Weekday())&s.Dow > 0
    	)
    	if s.Dom&starBit > 0 || s.Dow&starBit > 0 {
    		return domMatch && dowMatch
    	}
    	return domMatch || dowMatch
    }
    
  • Crash in cron.ParseStandard

    Crash in cron.ParseStandard

    Crash

    panic: runtime error: slice bounds out of range [:-1]

    Crash Log

    github.com/robfig/cron/v3.Parser.Parse({0x125d130}, {0x116435c, 0x9}) /Users/ljc/go/pkg/mod/github.com/robfig/cron/[email protected]/parser.go:99 +0x7bc github.com/robfig/cron/v3.ParseStandard(...) /Users/ljc/go/pkg/mod/github.com/robfig/cron/[email protected]/parser.go:230

    PoC

    cron.ParseStandard("TZ=TZ=TZ=")
    
  • [Bug] When outputting Entry, schedule, next, and previous showing default time

    [Bug] When outputting Entry, schedule, next, and previous showing default time

    When passing the following for AddFunc:

    _, err = reportingCron.AddFunc("0 7 * * *", func() { } An entry is registered in cron, when printing out said entry you receive a default time: logrus: time="2022-10-04T13:35:31-07:00" level=info msg="{1 0xc0001e0700 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0x8bdd40 0x8bdd40}" fmt.Println: {1 0xc0001e0700 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0x8bdd40 0x8bdd40}

Related tags
GoLang - Produces a binary suitable for use in shell scripts and cron jobs for rotating IAM credentials.

AWS-Rotate-IAM-Key aws-rotate-iam-key makes it easy to rotate your IAM keys whether they be in your ~/.aws/credentials file or else where. This work i

Feb 9, 2022
Library to work with MimeHeaders and another mime types. Library support wildcards and parameters.

Mime header Motivation This library created to help people to parse media type data, like headers, and store and match it. The main features of the li

Nov 9, 2022
Evolutionary optimization library for Go (genetic algorithm, partical swarm optimization, differential evolution)
Evolutionary optimization library for Go (genetic algorithm, partical swarm optimization, differential evolution)

eaopt is an evolutionary optimization library Table of Contents Changelog Example Background Features Usage General advice Genetic algorithms Overview

Dec 30, 2022
cross-platform, normalized battery information library

battery Cross-platform, normalized battery information library. Gives access to a system independent, typed battery state, capacity, charge and voltag

Dec 22, 2022
GoLang Library for Browser Capabilities Project

Browser Capabilities GoLang Project PHP has get_browser() function which tells what the user's browser is capable of. You can check original documenta

Sep 27, 2022
Go bindings for unarr (decompression library for RAR, TAR, ZIP and 7z archives)

go-unarr Golang bindings for the unarr library from sumatrapdf. unarr is a decompression library and CLI for RAR, TAR, ZIP and 7z archives. GoDoc See

Dec 29, 2022
Type-safe Prometheus metrics builder library for golang

gotoprom A Prometheus metrics builder gotoprom offers an easy to use declarative API with type-safe labels for building and using Prometheus metrics.

Dec 5, 2022
An easy to use, extensible health check library for Go applications.

Try browsing the code on Sourcegraph! Go Health Check An easy to use, extensible health check library for Go applications. Table of Contents Example M

Dec 30, 2022
An simple, easily extensible and concurrent health-check library for Go services
An simple, easily extensible and concurrent health-check library for Go services

Healthcheck A simple and extensible RESTful Healthcheck API implementation for Go services. Health provides an http.Handlefunc for use as a healthchec

Dec 30, 2022
Simple licensing library for golang.

license-key A simple licensing library in Golang, that generates license files containing arbitrary data. Note that this implementation is quite basic

Dec 24, 2022
Library for interacting with LLVM IR in pure Go.

llvm Library for interacting with LLVM IR in pure Go. Introduction Introductory blog post "LLVM IR and Go" Our Document Installation go get -u github.

Dec 28, 2022
atomic measures + Prometheus exposition library

About Atomic measures with Prometheus exposition for the Go programming language. This is free and unencumbered software released into the public doma

Sep 27, 2022
Morse Code Library in Go

morse Morse Code Library in Go Download and Use go get -u -v github.com/alwindoss/morse or dep ensure -add github.com/alwindoss/morse Sample Usage pac

Dec 30, 2022
A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell.

shellwords A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell. Installation go get github.com/Wing924

Sep 27, 2022
Notification library for gophers and their furry friends.
Notification library for gophers and their furry friends.

Shoutrrr Notification library for gophers and their furry friends. Heavily inspired by caronc/apprise. Quick Start As a package Using shoutrrr is easy

Jan 3, 2023
Go library for creating state machines
Go library for creating state machines

Stateless Create state machines and lightweight state machine-based workflows directly in Go code: phoneCall := stateless.NewStateMachine(stateOffHook

Jan 6, 2023
biogo is a bioinformatics library for Go
biogo is a bioinformatics library for Go

bíogo Installation $ go get github.com/biogo/biogo/... Overview bíogo is a bioinformatics library for the Go language. Getting help Help or simil

Jan 5, 2023
Functional programming library for Go including a lazy list implementation and some of the most usual functions.

functional A functional programming library including a lazy list implementation and some of the most usual functions. import FP "github.com/tcard/fun

May 21, 2022
FreeSWITCH Event Socket library for the Go programming language.

eventsocket FreeSWITCH Event Socket library for the Go programming language. It supports both inbound and outbound event socket connections, acting ei

Dec 11, 2022