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
Easy and fluent Go cron scheduling

goCron: A Golang Job Scheduling Package. goCron is a Golang job scheduling package which lets you run Go functions periodically at pre-determined inte

Jan 8, 2023
gron, Cron Jobs in Go.

gron Gron provides a clear syntax for writing and deploying cron jobs. Goals Minimalist APIs for scheduling jobs. Thread safety. Customizable Job Type

Dec 20, 2022
分布式定时任务库 distributed-cron
分布式定时任务库 distributed-cron

dcron 分布式定时任务库 原理 基于redis同步节点数据,模拟服务注册。然后将任务名 根据一致性hash 选举出执行该任务的节点。 流程图 特性 负载均衡:根据任务数据和节点数据均衡分发任务。 无缝扩容:如果任务节点负载过大,直接启动新的服务器后部分任务会自动迁移至新服务实现无缝扩容。

Dec 29, 2022
Run Jobs on a schedule, supports fixed interval, timely, and cron-expression timers; Instrument your processes and expose metrics for each job.

A simple process manager that allows you to specify a Schedule that execute a Job based on a Timer. Schedule manage the state of this job allowing you to start/stop/restart in concurrent safe way. Schedule also instrument this Job and gather metrics and optionally expose them via uber-go/tally scope.

Dec 8, 2022
Lightweight, fast and dependency-free Cron expression parser (due checker) for Golang (tested on v1.13 and above)

adhocore/gronx gronx is Golang cron expression parser ported from adhocore/cron-expr. Zero dependency. Very fast because it bails early in case a segm

Dec 30, 2022
Chadburn is a scheduler alternative to cron, built on Go and designed for Docker environments.

Chadburn - a job scheduler Chadburn is a modern and low footprint job scheduler for docker environments, written in Go. Chadburn aims to be a replacem

Dec 6, 2022
基于 Redis 和 Cron 的定时任务队列

RTask RTask 是 Golang 一款基于 Redis 和 Cron 的定时任务队列。 快速上手 您需要使用 Go Module 导入 RTask 工具包。 go get -u github.com/avtion/rtask 使用教程 package main import ( "con

Oct 27, 2021
A cron-like strategy plugin for HashiCorp Nomad Autoscaler

Nomad Autoscaler Cron Strategy A cron-like strategy plugin, where task groups are scaled based on a predefined scheduled. job "webapp" { ... group

Feb 14, 2022
Go-based runner for Cron Control

Cron Control Runner A Go-based runner for processing WordPress cron events, via Cron Control interfaces. Installation & Usage Clone the repo, and cd i

Jul 19, 2022
This package provides the way to get the previous timestamp or the next timestamp that satisfies the cron expression.

Cron expression parser Given a cron expression, you can get the previous timestamp or the next timestamp that satisfies the cron expression. I have us

May 3, 2022
Graceful shutdown with repeating "cron" jobs (running at a regular interval) in Go

Graceful shutdown with repeating "cron" jobs (running at a regular interval) in Go Illustrates how to implement the following in Go: run functions ("j

May 30, 2022
Zdpgo cron - 在golang中使用cron表达式并实现定时任务

zdpgo_cron 在golang中使用cron表达式并实现定时任务 项目地址:https://github.com/zhangdapeng520/zdpgo

Feb 16, 2022
Cloud-native, enterprise-level cron job platform for Kubernetes
Cloud-native, enterprise-level cron job platform for Kubernetes

Furiko Furiko is a cloud-native, enterprise-level cron and adhoc job platform for Kubernetes. The main website for documentation and updates is hosted

Dec 30, 2022
clockwork - Simple and intuitive job scheduling library in Go.
clockwork - Simple and intuitive job scheduling library in Go.

clockwork A simple and intuitive scheduling library in Go. Inspired by python's schedule and ruby's clockwork libraries. Example use package main imp

Jul 27, 2022
Simple, zero-dependency scheduling library for Go

go-quartz Simple, zero-dependency scheduling library for Go. About Inspired by the Quartz Java scheduler. Library building blocks Job interface. Any t

Dec 30, 2022
A persistent and flexible background jobs library for go.

Jobs Development Status Jobs is no longer being actively developed. I will still try my best to respond to issues and pull requests, but in general yo

Nov 21, 2022
Chrono is a scheduler library that lets you run your task and code periodically
Chrono is a scheduler library that lets you run your task and code periodically

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

Dec 26, 2022
go-sche is a golang library that lets you schedule your task to be executed later.

go-sche is a golang library that lets you schedule your task to be executed later.

Dec 24, 2022
Tiny library to handle background jobs.

bgjob Tiny library to handle background jobs. Use PostgreSQL to organize job queues. Highly inspired by gue Features Durable job storage At-least-ones

Nov 16, 2021