gron, Cron Jobs in Go.

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()
}
Comments
  • 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
  • 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
  • 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
null 0 Feb 14, 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.

Sherif Abdel-Naby 58 Dec 8, 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

Valentin Padurean (Ogg) 1 May 30, 2022
Gron transforms JSON into discrete assignments to make it easier to grep

gron Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it

null 0 Nov 11, 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 493 Nov 21, 2022
YTask is an asynchronous task queue for handling distributed jobs in golang

YTask is an asynchronous task queue for handling distributed jobs in golang

gojuukaze 232 Dec 24, 2022
Jenkins is a wonderful system for managing builds, and people love using its UI to configure jobs

Jenkins Job DSL Plugin Introduction Jenkins is a wonderful system for managing builds, and people love using its UI to configure jobs. Unfortunately,

Jenkins 1.8k Dec 20, 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

null 1 Nov 16, 2021
A way of scheduling volcano jobs

JobFlow 背景 volcano Volcano是CNCF 下首个也是唯一的基于Kubernetes的容器批量计算平台,主要用于高性能计算场景。 它提供了Kubernetes目前缺 少的一套机制,这些机制通常是机器学习大数据应用、科学计算、 特效渲染等多种高性能工作负载所需的。 现状:当前vol

BoCloud 22 Oct 12, 2022
Scheduler: Go jobs execution system

Scheduler Go jobs execution system. Inspired by CI/CD and Unity task scheduler.

Kyoto Framework 13 Jul 1, 2022
Executes jobs in separate GO routines. Provides Timeout, StartTime controls. Provides Cancel all running job before new job is run.

jobExecutor Library to execute jobs in GO routines. Provides for Job Timeout/Deadline (MaxDuration()) Job Start WallClock control (When()) Add a job b

Eswaran SK 0 Jan 10, 2022
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 215 Dec 17, 2022
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 2.7k Jan 8, 2023
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 10.7k Dec 25, 2022
分布式定时任务库 distributed-cron

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

libi 248 Dec 29, 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

Jitendra Adhikari 239 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

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

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

Avtion 2 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

Johan Siebens 5 Feb 14, 2022