gron, Cron Jobs in Go.

Related tags

golang scheduling cron-jobs
Overview

gron

Build Status Go Report Card GoDoc

Gron provides a clear syntax for writing and deploying cron jobs.

Goals

  • Minimalist APIs for scheduling jobs.
  • Thread safety.
  • Customizable Job Type.
  • Customizable Schedule.

Installation

$ go get github.com/roylee0704/gron

Usage

Create schedule.go

package main

import (
	"fmt"
	"time"
	"github.com/roylee0704/gron"
)

func main() {
	c := gron.New()
	c.AddFunc(gron.Every(1*time.Hour), func() {
		fmt.Println("runs every hour.")
	})
	c.Start()
}

Schedule Parameters

All scheduling is done in the machine's local time zone (as provided by the Go time package).

Setup basic periodic schedule with gron.Every().

gron.Every(1*time.Second)
gron.Every(1*time.Minute)
gron.Every(1*time.Hour)

Also support Day, Week by importing gron/xtime:

import "github.com/roylee0704/gron/xtime"

gron.Every(1 * xtime.Day)
gron.Every(1 * xtime.Week)

Schedule to run at specific time with .At(hh:mm)

gron.Every(30 * xtime.Day).At("00:00")
gron.Every(1 * xtime.Week).At("23:59")

Custom Job Type

You may define custom job types by implementing gron.Job interface: Run().

For example:

type Reminder struct {
	Msg string
}

func (r Reminder) Run() {
  fmt.Println(r.Msg)
}

After job has defined, instantiate it and schedule to run in Gron.

c := gron.New()
r := Reminder{ "Feed the baby!" }
c.Add(gron.Every(8*time.Hour), r)
c.Start()

Custom Job Func

You may register Funcs to be executed on a given schedule. Gron will run them in their own goroutines, asynchronously.

c := gron.New()
c.AddFunc(gron.Every(1*time.Second), func() {
	fmt.Println("runs every second")
})
c.Start()

Custom Schedule

Schedule is the interface that wraps the basic Next method: Next(p time.Duration) time.Time

In gron, the interface value Schedule has the following concrete types:

  • periodicSchedule. adds time instant t to underlying period p.
  • atSchedule. reoccurs every period p, at time components(hh:mm).

For more info, checkout schedule.go.

Full Example

package main

import (
	"fmt"
	"github.com/roylee0704/gron"
	"github.com/roylee0704/gron/xtime"
)

type PrintJob struct{ Msg string }

func (p PrintJob) Run() {
	fmt.Println(p.Msg)
}

func main() {

	var (
		// schedules
		daily     = gron.Every(1 * xtime.Day)
		weekly    = gron.Every(1 * xtime.Week)
		monthly   = gron.Every(30 * xtime.Day)
		yearly    = gron.Every(365 * xtime.Day)

		// contrived jobs
		purgeTask = func() { fmt.Println("purge aged records") }
		printFoo  = printJob{"Foo"}
		printBar  = printJob{"Bar"}
	)

	c := gron.New()

	c.Add(daily.At("12:30"), printFoo)
	c.AddFunc(weekly, func() { fmt.Println("Every week") })
	c.Start()

	// Jobs may also be added to a running Gron
	c.Add(monthly, printBar)
	c.AddFunc(yearly, purgeTask)

	// Stop Gron (running jobs are not halted).
	c.Stop()
}
Issues
  • Run Every hour at a specific time

    Run Every hour at a specific time

    gron.Every(1 * time.Hour).At("00:30"), func() { fmt.Println("Every hour on the half hour") })

    crontab: 0 30 * * * *

    My use case is that I want to run every hour: job1 at 00:30 job2 at 00:40

    opened by hexadecy 5
  • Feature/add wg for job

    Feature/add wg for job

    opened by Fred07 1
  • Feature/use context to control goroutines

    Feature/use context to control goroutines

    Remove HandleSignals()

    Add context to the gron, and listen to context.Done() to trigger GracefullyStop()

    opened by Fred07 1
  • Fix data race in Add method

    Fix data race in Add method

    It uses a mutex lock on the global variables 'running' and 'entries'.

    Defines a new method 'isActive' to deal with re-entrant lock issue.

    In reference to the issue #3.

    opened by pravj 0
  • is it possible to run job once across multiple instances?

    is it possible to run job once across multiple instances?

    Hi Is it possible to execute the cron jobs only once across multiple instances? If no, What could a better solution to achieve this?

    opened by amarjeetanandsingh 0
  • fix the bug of dynamic adding job in cron.go

    fix the bug of dynamic adding job in cron.go

    fix the bug of dynamic adding job ( the case: c.running ==true ), the calculation of new time must be done before the next round for loop.

    opened by sstshenshutao 0
  • reset 方法是会把时间设置为UTC时区时间吗,为什么不是Local?

    reset 方法是会把时间设置为UTC时区时间吗,为什么不是Local?

    func (as atSchedule) reset(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day(), as.hh, as.mm, 0, 0, time.UTC) }

    opened by php2go 0
  • [Feature Request] Jobs monitoring

    [Feature Request] Jobs monitoring

    Thanks for awesome work! It would be great if the gron can have some info for all added jobs (runnning, scheduled, ...)

    opened by qmn1711 0
  • add cancel support

    add cancel support

    A cronjob may need be canceled before run in some situation. Sugguest to add this feature

    opened by chennqqi 0
  • UTC time using in AtSchedule

    UTC time using in AtSchedule

    Hi, You mentioned ‘All scheduling is done in the machine's local time zone (as provided by the Go time package).’ in the REAMME.md.

    In the implementation of AtSchedule a UTC time is used in reset() function. Shouldn't that be time.Local?

    opened by TechieYork 1
  • Data race in Add method

    Data race in Add method

    Using channel based synchronization in Add method prevents the data races when the cron instance is running.

    Although, it can't stop them when the cron instance is inactive.

    package main
    
    import (
      "fmt"
      "time"
      "github.com/roylee0704/gron"
    )
    
    func main() {
      blocker := make(chan int)
      g := gron.New()
    
      g.AddFunc(gron.Every(4*time.Second), func() {
        fmt.Println("J-1/4")
      })
      g.AddFunc(gron.Every(3*time.Second), func() {
        fmt.Println("J-2/3")
      })
    
      // this will access (write) the shared state 'entries' concurrently
      go func() {
        g.AddFunc(gron.Every(2*time.Second), func() {
          fmt.Println("J-3/2")
        })
      }()
    
      g.Start()
    
      <-blocker
    }
    

    Running this with Golang's Race Detector will report the data race.

    $ go run -race main.go
    

    I propose to use Mutex for this particular case.

    cc @roylee0704

    opened by pravj 0
  • use local time instead of utc for atScheduling

    use local time instead of utc for atScheduling

    I got GMT+3 time zone, so when i write gron.Every(1 * xtime.Day).At("19:32") i expect function will be triggered at 19:32 local time, not UTC time (which is 3 hours difference in my case). Tests are green, looks like no side effects.

    opened by postromantic 1
Owner
roylee0704
Software Engineer
roylee0704
a cron library for go

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: im

Rob Figueiredo 8k Jun 20, 2021
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

Alex Browne 482 May 31, 2021
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.

Sherif Abdel-Naby 52 May 9, 2021
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

Jitendra Adhikari 162 Jun 10, 2021
A simple job scheduler backed by Postgres.

A simple job scheduler backed by Postgres used in production at https://operand.ai. Setup needs two environment variables, SECRET and ENDPOINT. The se

Morgan Gallant 6 May 31, 2021
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

Procyon 97 Jun 8, 2021
You had one job, or more then one, which can be done in steps

Leprechaun Leprechaun is tool where you can schedule your recurring tasks to be performed over and over. In Leprechaun tasks are recipes, lets observe

Strahinja 82 Apr 4, 2021
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

Go Co Op 869 Jun 12, 2021
Framework for performing work asynchronously, outside of the request flow

JobRunner JobRunner is framework for performing work asynchronously, outside of the request flow. It comes with cron to schedule and queue job functio

Bam Azizi 852 Jun 8, 2021
goCron: A Golang Job Scheduling Package.

goCron: A Golang Job Scheduling Package.

辣椒面 2.6k Jun 11, 2021
Efficient and reliable background processing for Go

CurlyQ CurlyQ provides a simple, easy-to-use interface for performing background processing in Go. It supports scheduled jobs, job deduplication, and

James McMath 112 Apr 25, 2021
A simple Cron library for go that can execute closures or functions at varying intervals, from once a second to once a year on a specific date and time. Primarily for web applications and long running daemons.

Cron.go This is a simple library to handle scheduled tasks. Tasks can be run in a minimum delay of once a second--for which Cron isn't actually design

Robert K 202 Jun 12, 2021
Job scheduling made easy.

scheduler Job scheduling made easy. Scheduler allows you to schedule recurrent jobs with an easy-to-read syntax. Inspired by the article Rethinking Cr

Carles Cerezo Guzmán 367 Jun 7, 2021
定时任务管理系统

gocron - 定时任务管理系统 项目简介 使用Go语言开发的轻量级定时任务集中调度和管理系统, 用于替代Linux-crontab 查看文档 原有的延时任务拆分为独立项目延迟队列 功能特性 Web界面管理定时任务 crontab时间表达式, 精确到秒 任务执行失败可重试 任务执行超时, 强制结束

qiang.ou 3.5k Jun 14, 2021