a cron library for go

Related tags

cron
Overview

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.

Issues
  • 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!!!!!!!

    opened by ttlv 16
  • Version 2

    Version 2

    Hello, Is v2 still supported ? Are recent fixes on master planned to be ported to v2 ?

    opened by chambo-e 15
  • 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.

    opened by elgs 15
  • how can i remove job when Cron is running?

    how can i remove job when Cron is running?

    func (c *Cron) RemoveJob(identifier string) { //remove job by identifier }

    i think add a method like this is useful

    opened by cgyy 14
  • 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.

    opened by qiukeren 13
  • 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.

    opened by dennisfrancis 12
  • 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
    }
    
    opened by bruth 11
  • Protecting start from double runs.

    Protecting start from double runs.

    opened by pascallouisperez 9
  • 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.

    opened by MirkoWu 9
  • 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.

    opened by vegasje 9
  • Run Cron Indefinitely

    Run Cron Indefinitely

    Hi, I'm wondering if there is a way to run the CRON job indefinitely instead of specifying a sleep between start & stop as below: // create a cron and start it c := cron.New() c.Start()

    // cron-job runs for the duration hours: jobPeriod as mentioned in the properties file.
    if jobPeriod >= 1 {
    	time.Sleep(time.Duration(jobPeriod))
    }
    
    c.Stop()
    
    opened by udayravuri 0
  • Job executed even after killing the process?

    Job executed even after killing the process?

    Hello, thank you for this great library. I am using it in my side projects and I love it.

    There is an issue that I am seeing, which might not about this library, but I see this for the first time using it.

    I made a program that executes a function everyday at certain time, then ran it background. Then I killed it using kill -9 {PID} and re-ran the code (did this multiple time).

    The next day, I found out that the function was executed multiple times. Is this expected? When I rebooted the computer and ran the program once, the function is executed just one time, so I don't think I mistakenly ran the function multiple times in the code. Thanks!

    opened by jazzsaxmafia 0
  • Run every two days on odd

    Run every two days on odd "day"

    Hey!

    I don't know if it's a bug, but I need to have two crons, one on odd day, one on even. I have this cron definition:

    CronJob A: 0 12 1-31/2 * *
    CronJob B: 0 12 2-30/2 * *
    

    It seemed to work for the first execution, but two days after, it didn't run... Don't know if it's a known bug or a misuse of us :)

    Thanks!

    opened by Emixam23-FCMS 0
  • cron/byTime: Optimization determine the nexe entry

    cron/byTime: Optimization determine the nexe entry

    Optimization determine the nexe entry,

    from sort.Sort() to byTime.Min(),

    sort.Sort: one call to data.Len and O(n*log(n)) calls to data.Less and data.Swap, byTime.Min: O(n) calls to data.Less and data.Swap.

    opened by secake 0
  • [feature] ability to immediately start an @every job

    [feature] ability to immediately start an @every job

    Would it be possible to add an option to start jobs scheduled as @every immediately (and not after the interval)?

    The docs mention that

    For example, "@every 1h30m10s" would indicate a schedule that activates after 1 hour, 30 minutes, 10 seconds, and then every interval after that.

    I believe that there it would be interesting to have the immediate start - for instance, I need to do

    googleCalendar()
    forecast()
    temperature()
    c := cron.New()
    c.AddFunc("@every 1min", googleCalendar)
    c.AddFunc("@every 15min", forecast)
    c.AddFunc("@every 12min", temperature)
    c.Start()
    

    instead of, say

    c := cron.New({intervalRunAtStartup: true})
    c.AddFunc("@every 1min", googleCalendar)
    c.AddFunc("@every 15min", forecast)
    c.AddFunc("@every 12min", temperature)
    c.Start()
    

    (see also https://github.com/robfig/cron/issues/396)

    opened by wsw70 0
  • Is that thread safe?

    Is that thread safe?

    If i set cron as a global variable, all the AddFunc Remove methods with it will be thread safe?

    opened by dzpt 0
  • Use time.Truncate instead of explicit modulo/subtraction.

    Use time.Truncate instead of explicit modulo/subtraction.

    time.Duration.Truncate and time.Time.Truncate were introduced in Go 1.9 and 1.1, and thus I guess they are okay.

    opened by favonia 0
  • Can you set a timed task in milliseconds?

    Can you set a timed task in milliseconds?

    Can you set a timed task in milliseconds?

    opened by beyondyinjl2 0
Owner
Rob Figueiredo
Rob Figueiredo
Auto daily report for HITSZ Students.

auto-report Auto daily report for HITSZ Students. Usage Report Once Golang go run main.go -u your-studentID -p your-password -e your-email Docker dock

null 36 Aug 19, 2021
generate my_github status using GitHub Actions

generate my_github status using GitHub Actions

yihong 36 Sep 9, 2021
今日热榜,一个获取各大热门网站热门头条的聚合网站,使用Go语言编写,多协程异步快速抓取信息

今日热榜是一个获取各大热门网站热门头条的聚合网站,使用Go语言编写,多协程异步快速抓取信息,预览:http://mo.fish 安装教程 编译 cd {root_path} # 项目根目录

今日热榜 4.2k Sep 14, 2021
server for dozenplans

DozenPlans Server 学习养成计划主要是针对考研学生用户的任务管理系统, 用户可以添加 学习 任务, 每个任务都有自己的主题、 完成时间和优先级, 根据设定的完成时间和优先级对 用户进行不同频率的提醒, 直到其完成该任务, 任务可以设定提醒频率和时间期限, 避免导致任务越堆积越多, 除

null 3 Jul 8, 2021
ghw - Golang HardWare discovery/inspection library

ghw - Golang HardWare discovery/inspection library ghw is a small Golang library providing hardware inspection and discovery for Linux and Windows.

Jay Pipes 1k Sep 10, 2021
Go implementation of the XDG Base Directory Specification and XDG user directories

xdg Provides an implementation of the XDG Base Directory Specification. The specification defines a set of standard paths for storing application file

Adrian-George Bostan 130 Sep 13, 2021
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

Milan Nikolic 147 Aug 21, 2021
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

bíogo 303 Aug 27, 2021
Easily create & extract archives, and compress & decompress files of various formats

archiver Introducing Archiver 3.1 - a cross-platform, multi-format archive utility and Go library. A powerful and flexible library meets an elegant CL

Matt Holt 3.3k Sep 10, 2021
Prometheus instrumentation library for Go applications

Prometheus Go client library This is the Go client library for Prometheus. It has two separate parts, one for instrumenting application code, and one

Prometheus 3.3k Sep 7, 2021
Elegant generics for Go

genny - Generics for Go Install: go get github.com/cheekybits/genny ===== (pron. Jenny) by Mat Ryer (@matryer) and Tyler Bunnell (@TylerJBunnell). Un

null 1.6k Sep 15, 2021
Emojis for Go 😄🐢🚀

turtle Emojis for Go ?? ?? ?? Reference Follow this link to view the reference documentation: GoDoc Reference ?? Installation Library To install the t

Raphael Pierzina 124 Aug 17, 2021
A library for parallel programming in Go

pargo A library for parallel programming in Go Package pargo provides functions and data structures for expressing parallel algorithms. While Go is pr

null 168 Jul 23, 2021
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

Anton Ohorodnyk 25 Aug 24, 2021
Super short, fully unique, non-sequential and URL friendly Ids

Generator of unique non-sequential short Ids The package shortidenables the generation of short, fully unique, non-sequential and by default URL frien

teris.io 695 Aug 31, 2021
safe and easy casting from one type to another in Go

cast Easy and safe casting from one type to another in Go Don’t Panic! ... Cast What is Cast? Cast is a library to convert between different go types

Steve Francia 1.7k Sep 12, 2021
Flow-based and dataflow programming library for Go (golang)

GoFlow - Dataflow and Flow-based programming library for Go (golang) Status of this branch (WIP) Warning: you are currently on v1 branch of GoFlow. v1

Vladimir Sibirov 1.3k Sep 11, 2021
wkhtmltopdf Go bindings and high level interface for HTML to PDF conversion

wkhtmltopdf Go bindings and high level interface for HTML to PDF conversion. Implements wkhtmltopdf Go bindings. It can be used to convert HTML docume

Adrian-George Bostan 65 Sep 10, 2021
Yubigo is a Yubikey client API library that provides an easy way to integrate the Yubico Yubikey into your existing Go-based user authentication infrastructure.

yubigo Yubigo is a Yubikey client API library that provides an easy way to integrate the Yubikey into any Go application. Installation Installation is

Geert-Johan Riemer 116 Aug 20, 2021