goCron: A Golang Job Scheduling Package.

Related tags

gocron
Overview

Note from current maintainers:

A currently maintained fork of this project has been migrated to https://github.com/go-co-op/gocron

Disclaimer: we (the maintainers) tried, with no luck, to get in contact with Jason (the repository owner) in order to add new maintainers or leave the project within an organization. Unfortunately, he hasn't replied for months now (March, 2020).

So, we decided to move the project to a new repository (as stated above), in order to keep the evolution of the project coming from as many people as possible. Feel free to reach over!

goCron: A Golang Job Scheduling Package.

This package is currently looking for new maintainers (cause @jasonlvhit is in ICU). Please message @jasonlvhit if you are interested.

GgoDoc Go Report Card

goCron is a Golang job scheduling package which lets you run Go functions periodically at pre-determined interval using a simple, human-friendly syntax.

goCron is a Golang implementation of Ruby module clockwork and Python job scheduling package schedule, and personally, this package is my first Golang program, just for fun and practice.

See also this two great articles:

If you want to chat, you can find us at Slack!

Back to this package, you could just use this simple API as below, to run a cron scheduler.

package main

import (
	"fmt"
	"time"

	"github.com/jasonlvhit/gocron"
)

func task() {
	fmt.Println("I am running task.")
}

func taskWithParams(a int, b string) {
	fmt.Println(a, b)
}

func main() {
	// Do jobs without params
	gocron.Every(1).Second().Do(task)
	gocron.Every(2).Seconds().Do(task)
	gocron.Every(1).Minute().Do(task)
	gocron.Every(2).Minutes().Do(task)
	gocron.Every(1).Hour().Do(task)
	gocron.Every(2).Hours().Do(task)
	gocron.Every(1).Day().Do(task)
	gocron.Every(2).Days().Do(task)
	gocron.Every(1).Week().Do(task)
	gocron.Every(2).Weeks().Do(task)

	// Do jobs with params
	gocron.Every(1).Second().Do(taskWithParams, 1, "hello")

	// Do jobs on specific weekday
	gocron.Every(1).Monday().Do(task)
	gocron.Every(1).Thursday().Do(task)

	// Do a job at a specific time - 'hour:min:sec' - seconds optional
	gocron.Every(1).Day().At("10:30").Do(task)
	gocron.Every(1).Monday().At("18:30").Do(task)
	gocron.Every(1).Tuesday().At("18:30:59").Do(task)

	// Begin job immediately upon start
	gocron.Every(1).Hour().From(gocron.NextTick()).Do(task)

	// Begin job at a specific date/time
	t := time.Date(2019, time.November, 10, 15, 0, 0, 0, time.Local)
	gocron.Every(1).Hour().From(&t).Do(task)

	// NextRun gets the next running time
	_, time := gocron.NextRun()
	fmt.Println(time)

	// Remove a specific job
	gocron.Remove(task)

	// Clear all scheduled jobs
	gocron.Clear()

	// Start all the pending jobs
	<- gocron.Start()

	// also, you can create a new scheduler
	// to run two schedulers concurrently
	s := gocron.NewScheduler()
	s.Every(3).Seconds().Do(task)
	<- s.Start()
}

and full test cases and document will be coming soon (help is wanted! If you want to contribute, pull requests are welcome).

If you need to prevent a job from running at the same time from multiple cron instances (like running a cron app from multiple servers), you can provide a Locker implementation and lock the required jobs.

gocron.SetLocker(lockerImplementation)
gocron.Every(1).Hour().Lock().Do(task)

Once again, thanks to the great works of Ruby clockwork and Python schedule package. BSD license is used, see the file License for detail.

Looking to contribute? Try to follow these guidelines:

  • Use issues for everything
  • For a small change, just send a PR!
  • For bigger changes, please open an issue for discussion before sending a PR.
  • PRs should have: tests, documentation and examples (if it makes sense)
  • You can also contribute by:
    • Reporting issues
    • Suggesting new features or enhancements
    • Improving/fixing documentation

Have fun!

Issues
  • Adds production ready safety

    Adds production ready safety

    This PR was requested to be opened. It is a series of changes that make the code more production safe. In general it's not good practice to panic in source code that is meant to be imported. The user should be able to "catch" based on errors and not have to rely on defer recover

    opened by marcsantiago 12
  • Interval doesn't work correctly

    Interval doesn't work correctly

    I try to run a task every 3 seconds, but it still runs every second:

    func Hello() {
    	fmt.Printf("hello %d\n", time.Now().Unix())
    }
    
    func main() {
    	gocron.Every(3).Seconds().Do(Hello)
    	<-gocron.Start()
    }
    

    The result is:

    hello 1561223112
    hello 1561223113
    hello 1561223114
    hello 1561223115
    hello 1561223116
    hello 1561223117
    hello 1561223118
    
    4 - Done bug 
    opened by aj3423 12
  • 100% CPU Usage

    100% CPU Usage

    Gocron is using 100% of one core, 100% of the time.

    You don't even have to schedule anything, just calling gocron.Start() will do it.

    Any thoughts?

    bug 
    opened by camronlevanger 10
  • Check if a job was scheduled before

    Check if a job was scheduled before

    This is useful when you need to know if a task should be scheduled or not based on the fact that it is already scheduled (or not)

    opened by shackra 10
  • Jobs start at different time

    Jobs start at different time

    Hey, I'll try and explain this as best as possible.

    Say I set a task at 09:30

    scheduler := gocron.NewScheduler() scheduler.Every(1).Day().At("09:30").Do(someTask)

    Say my task takes 10 minutes to complete at 09:30 and ends at 09:40, the next day, the task starts at 9:40, and repeats this, so eventually this task will be running at a completely different time if left forever.

    Not sure if you've noticed this, but i thought it would be worth mentioning.

    Thanks!

    4 - Done bug 
    opened by Noy 10
  • Run task just once

    Run task just once

    Is there a idiomatic way of scheduling a task to run just once? That is to say, create a schedule that is ran once and then cleared?

    The only way I can think of is:

    func scheduleOnce() {
      s := gocron.NewScheduler()
      s.Every(1).Day().At("10:30").Do(foo, s)
      <- s.Start()
    }
    
    func foo(s *gocron.Scheduler) {
      // My code
      s.Clear()
    }
    

    Which I haven't actually tested yet but I figured this would be a solution to my problem.

    opened by danhardman 10
  • DoSafely() doesn't actually do anything

    DoSafely() doesn't actually do anything

    When running a task with DoSafely, it never actually performs the task.

    Here is an example main.go file:

    package main
    
    import (
    	"io/ioutil"
    	"log"
    
    	"github.com/jasonlvhit/gocron"
    )
    
    func task() {
    	log.Println("I am runnning task.")
    	d1 := []byte("hello\ngo\n")
    	ioutil.WriteFile("/tmp/dat1", d1, 0644)
    }
    
    func main() {
    	s := gocron.NewScheduler()
    	s.Every(3).Seconds().DoSafely(task)
    	<-s.Start()
    }
    

    Test it out - if you swap in Do for DoSafely it works as expected, outputs to the terminal and writes the file. With DoSafely nothing happens.

    2 - Working <= 5 bug 
    opened by JohnRoesler 9
  • add func BeginNow to start job immediately

    add func BeginNow to start job immediately

    • Adds the BeginNow function and a test (thoughts on the func name? words are hard...)
      • Usage looks like gocron.Every(1).Hour().BeginNow().Do(task)
      • resolves https://github.com/jasonlvhit/gocron/issues/115
    • sets const values for seconds, minutes, etc.
    • Address golint requirement for exported functions to have comments in the form of funcName ... description
    3 - Review enhancement 
    opened by JohnRoesler 8
  • Day of the Week not working?

    Day of the Week not working?

    I have written a simple program that writes hello at a certain time on both Monday and Friday:

    package main
    import (
      "fmt"
      "github.com/jasonlvhit/gocron"
    )
    
    func main() {
      gocron.Every(1).Monday().At("15:54").Do(func() { fmt.Println("Hi from Monday!") })
      gocron.Every(1).Friday().At("15:54").Do(func() { fmt.Println("Hi from Friday!") })
      <-gocron.Start()
    }
    
    

    The output today (Friday) at 15:54 on my OS X machine was this:

    Hi from Monday!
    Hi from Friday!
    

    Also, it is not relevant that the two times were the same. This

      gocron.Every(1).Monday().At("16:13").Do(func() { fmt.Println("Hi from Friday!") })
      gocron.Every(1).Friday().At("16:14").Do(func() { fmt.Println("Hi from Monday!") })
    

    produced this by 16:14:

    Hi from Friday!
    Hi from Monday!
    

    Any ideas?

    bug 
    opened by lgessler 8
  • Use stringer instead of string constants for time units

    Use stringer instead of string constants for time units

    This is just a good practice I guess. Also, looks cleaner.

    3 - Review 
    opened by arjunmahishi 6
  • About task execution time

    About task execution time

    My task is set to execute time, but it does not take effect。 I want to execute once every minute, at 00 seconds 。So I used this method。 At。But the exection is 56 seconds。

    For example, gocron.Every(1).Minute().At("00:00:00").Do(db.task) but run time is I0611 15:40:55.602110 image

    opened by rtywei 1
  • exec time

    exec time

    I want set last day of every month to exec command.
    I use "0 0 8 28-31 * * " ,but not what I wanted Would you please tell me what I should do?

    opened by Soberabsurd 1
  • #166 Schedule task every X hours from a date in the past

    #166 Schedule task every X hours from a date in the past

    Also fix the tests that didn't pass near year time change day (Mar 25, for example)

    opened by naduda 1
  • Async Scheduler

    Async Scheduler

    Every 3 seconds call function process but sometimes has delay to response, accumulating the time..

    How call async function every 3 seconds?

    s := gocron.NewScheduler()
    s.Every(3).Seconds().Do(task)
    <- s.Start()
    
    opened by darlandieterich 2
  • Lock function, still run multiple times on multiple server instances

    Lock function, still run multiple times on multiple server instances

    i used lock implementation on redis, but it still run cron multiple times on multiple instances, i have 4 instances and it still run 4 times

    locker := p.schedulerLockerRepo
    gocron.SetLocker(locker)
    go p.paymentDailyReminderWorker()
    
    func paymentDailyReminderWorker() {
    	reminderScheduler := gocron.NewScheduler()
    	if err := reminderScheduler.Every(1).Day().At(c.config.DailyReminderClock).Lock().Do(c.processPaymentReminder); err == nil {
    		c.logger.Info().Str("reminder_at", c.config.DailyReminderClock).Msg("payment daily reminder worker started")
    		<-reminderScheduler.Start()
    	}
    }
    
    opened by g-graziano 3
  • remove job by tag

    remove job by tag

    opened by amirhosseinvz94 1
  • Fix issue with

    Fix issue with "Scheduled" panics when job not scheduled

    #129 issue

    This code are panics:

    func One() {}
    func Two() {}
    func main() {
    	scheduler := gocron.NewScheduler()
    	scheduler.Every(1).Day().Do(One)
    	// and next panics
    	exists := scheduler.Scheduled(Two)
    	fmt.Println(exists)
    }
    
    opened by ferryvg 0
  • Expressing doubts

    Expressing doubts

    图片
    opened by lijinghuatongxue 4
  • Fix PR #133 so that it does not break RunAll

    Fix PR #133 so that it does not break RunAll

    First sorry about #136. Obviously two different competing concepts here.

    I think the solution here is to distinguish between the two concepts - add a simply bool to the run() function.

    opened by wishdev 0
  • Implement custom logger

    Implement custom logger

    I think we should make it compatible with the custom logger modules created in the applications. In this way, job status can be monitored in autonomous state. I can write directly, if that's okay.

    2 - Working <= 5 enhancement 
    opened by akdilsiz 5
Releases(v0.0.1)
Owner
辣椒面
辣椒面
定时任务管理系统

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

qiang.ou 3.6k Jul 25, 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 952 Jul 22, 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 53 Jul 2, 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
Job worker service that provides an API to run arbitrary Linux processes.

Job Scheduler Summary Prototype job worker service that provides an API to run arbitrary Linux processes. Overview Library The library (Worker) is a r

Renato Guimarães 5 Jun 2, 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
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 104 Jul 20, 2021
A lightweight job scheduler based on priority queue with timeout, retry, replica, context cancellation and easy semantics for job chaining. Build for golang web apps.

Table of Contents Introduction What is RIO? Concern An asynchronous job processor Easy management of these goroutines and chaining them Introduction W

Supratim Samanta 36 Jul 7, 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 368 Jul 10, 2021
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

roylee0704 863 Jul 20, 2021
Distributed Task Scheduling System|分布式定时任务调度平台

Crocodile Distributed Task Scheduling System English | 中文 Introduction A distributed task scheduling system based on Golang that supports http request

labulaka521 591 Jul 18, 2021
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

Eugene R. 145 Jul 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
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 861 Jul 27, 2021