Volver al ranking

go-co-op/gocron

Go

Easy and fluent Go cron scheduling. This is a fork from https://github.com/jasonlvhit/gocron

cronschedulergocrongolang-job-schedulinggolangclockworkschedulehacktoberfest
Crecimiento de estrellas
Estrellas
7.1k
Forks
349
Crecimiento semanal
Issues
0
7.1k7.1k7.1k
18 jul19 jul20 jul22 jul
ArtefactosGo Modulesgo get github.com/go-co-op/gocron
README

gocron: A Golang Job Scheduling Package

CI State Go Report Card Go Doc

gocron is a job scheduling package which lets you run Go functions at pre-determined intervals.

Looking for a visual interface? Check out gocron-ui — a lightweight web dashboard to monitor, trigger, and manage your gocron jobs in real time.

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

Quick Start

go get github.com/go-co-op/gocron/v2
package main

import (
	"fmt"
	"time"

	"github.com/go-co-op/gocron/v2"
)

func main() {
	// create a scheduler
	s, err := gocron.NewScheduler()
	if err != nil {
		// handle error
	}

	// add a job to the scheduler
	j, err := s.NewJob(
		gocron.DurationJob(
			10*time.Second,
		),
		gocron.NewTask(
			func(a string, b int) {
				// do things
			},
			"hello",
			1,
		),
	)
	if err != nil {
		// handle error
	}
	// each job has a unique id
	fmt.Println(j.ID())

	// start the scheduler
	s.Start()

	// block until you are ready to shut down
	select {
	case <-time.After(time.Minute):
	}

	// when you're done, shut it down
	err = s.Shutdown()
	// or for context-aware teardown:
	// err = s.ShutdownWithContext(ctx)
	if err != nil {
		// handle error
	}
}

Examples

Articles & Blog Posts

Community articles and tutorials about using gocron:

Concepts

  • Job: The job encapsulates a "task", which is made up of a go function and any function parameters. The Job then provides the scheduler with the time the job should next be scheduled to run.
  • Scheduler: The scheduler keeps track of all the jobs and sends each job to the executor when it is ready to be run.
  • Executor: The executor calls the job's task and manages the complexities of different job execution timing requirements (e.g. singletons that shouldn't overrun each other, limiting the max number of jobs running)

Features

Job types

Jobs can be run at various intervals.

  • Duration: Jobs can be run at a fixed time.Duration.
  • Random duration: Jobs can be run at a random time.Duration between a min and max.
  • Cron: Jobs can be run using a crontab.
  • Daily: Jobs can be run every x days at specific times.
  • Weekly: Jobs can be run every x weeks on specific days of the week and at specific times.
  • Monthly: Jobs can be run every x months on specific days of the month and at specific times.
  • One time: Jobs can be run at specific time(s) (either once or many times).

Interval Timing

Jobs can be scheduled with different interval timing modes.

  • Interval from scheduled time (default): By default, jobs calculate their next run time from when they were scheduled to start, resulting in fixed intervals regardless of execution time. Good for cron-like scheduling at predictable times.
  • Interval from completion time: Jobs can calculate their next run time from when they complete, ensuring consistent rest periods between executions. Ideal for rate-limited APIs, resource-intensive jobs, and scenarios where execution time varies.

Concurrency Limits

Jobs can be limited individually or across the entire scheduler.

  • Per job limiting with singleton mode: Jobs can be limited to a single concurrent execution that either reschedules (skips overlapping executions) or queues (waits for the previous execution to finish).
  • Per scheduler limiting with limit mode: Jobs can be limited to a certain number of concurrent executions across the entire scheduler using either reschedule (skip when the limit is met) or queue (jobs are added to a queue to wait for the limit to be available).
  • Note: A scheduler limit and a job limit can both be enabled.

Distributed instances of gocron

Multiple instances of gocron can be run.

  • Elector: An elector can be used to elect a single instance of gocron to run as the primary with the other instances checking to see if a new leader needs to be elected.
    • Implementations: go-co-op electors (don't see what you need? request on slack to get a repo created to contribute it!)
  • Locker: A locker can be used to lock each run of a job to a single instance of gocron. Locker can be at job or scheduler, if it is defined both at job and scheduler then locker of job will take precedence.
    • See Notes in the doc for Locker for details and limitations of the locker design.
    • Implementations: go-co-op lockers (don't see what you need? request on slack to get a repo created to contribute it!)

Events

Job events can trigger actions.

Options

Many job and scheduler options are available.

  • Job options: Job options can be set when creating a job using NewJob.
  • Global job options: Global job options can be set when creating a scheduler using NewScheduler and the WithGlobalJobOptions option.
  • Scheduler options: Scheduler options can be set when creating a scheduler using NewScheduler.

Logging

Logs can be enabled.

  • Logger: The Logger interface can be implemented with your desired logging library. The provided NewLogger uses the standard library's log package.

Metrics

Metrics may be collected from the execution of each job and scheduler lifecycle events.

  • Monitor: A monitor can be used to collect metrics for each job from a scheduler.

    • Implementations: There are currently no open source implementations of the Monitor interface available. We'd love for you to be the first to contribute one! Check out the Monitor interface documentation to get started, or reach out on Slack if you'd like to discuss your implementation.
  • MonitorStatus: Extends Monitor with status and error tracking for each job.

    • Implementations: There are currently no open source implementations of the MonitorStatus interface available. We'd love for you to be the first to contribute one! Check out the MonitorStatus interface documentation to get started, or reach out on Slack if you'd like to discuss your implementation.
  • SchedulerMonitor: A scheduler monitor provides comprehensive observability into scheduler and job lifecycle events.

    Available Metrics:

    • Scheduler Lifecycle: SchedulerStarted, SchedulerStopped, SchedulerShutdown
    • Job Management: JobRegistered, JobUnregistered - track jobs added/removed from scheduler
    • Job Execution: JobStarted, JobRunning, JobCompleted, JobFailed - monitor job execution flow
    • Performance: JobExecutionTime, JobSchedulingDelay - measure job duration and scheduling lag
    • Concurrency: ConcurrencyLimitReached - detect when singleton or limit mode constraints are hit

    Derived Metrics (calculable from events):

    • Error rate: JobFailed / (JobCompleted + JobFailed)
    • Average execution time: from JobExecutionTime events
    • Active jobs: JobRegistered - JobUnregistered
    • Current queue depth: JobStarted - (JobCompleted + JobFailed)

    Example - Prometheus Integration:

    type PrometheusMonitor struct {
        jobsCompleted   prometheus.Counter
        jobsFailed      prometheus.Counter
        executionTime   prometheus.Histogram
        schedulingDelay prometheus.Histogram
    }
    
    func (p *PrometheusMonitor) JobExecutionTime(job gocron.Job, duration time.Duration) {
        p.executionTime.Observe(duration.Seconds())
    }
    
    func (p *PrometheusMonitor) JobSchedulingDelay(job gocron.Job, scheduled, actual time.Time) {
        if delay := actual.Sub(scheduled); delay > 0 {
            p.schedulingDelay.Observe(delay.Seconds())
        }
    }
    
    // Initialize scheduler with monitor
    s, _ := gocron.NewScheduler(gocron.WithSchedulerMonitor(monitor))
    

    Use Cases: Prometheus metrics, custom dashboards, alerting systems, performance monitoring

    • Implementations: There are currently no open source implementations of the SchedulerMonitor interface available. We'd love for you to be the first to contribute one! Check out the SchedulerMonitor interface documentation to get started, or reach out on Slack if you'd like to discuss your implementation.

Testing

The gocron library is set up to enable testing.

Supporters

We appreciate the support for free and open source software!

This project is supported by:

JetBrains

JetBrains logo

Sentry

Sentry logo
Repositorios relacionados
xuxueli/xxl-job

A distributed task scheduling framework.(分布式任务调度平台XXL-JOB)

JavaMavenGNU General Public License v3.0xxl-jobjob
xuxueli.com/xxl-job/
30.4k11.5k
0xJacky/nginx-ui

Yet another WebUI for Nginx

GoGo ModulesGNU Affero General Public License v3.0nginxwebui
nginxui.com
11.3k847
healthchecks/healthchecks

Open-source cron job and background task monitoring service, written in Python & Django

PythonPyPIBSD 3-Clause "New" or "Revised" Licensecrondevops
healthchecks.io
10.2k993
agenda/agenda

Lightweight job scheduling for Node.js

HTMLOthercronscheduler
agenda.github.io/agenda/
9.7k847
apache/shardingsphere-elasticjob

Distributed scheduled job

JavaMavenApache License 2.0scheduled-jobscron
8.2k3.3k
gdy666/lucky

软硬路由公网神器,ipv6/ipv4 端口转发,反向代理,DDNS,WOL,ipv4 stun内网穿透,cron,acme,rclone,ftp,webdav,filebrowser

GoGo ModulesMIT Licenseddnsipv6
8k727
PowerJob/PowerJob

Enterprise job scheduling middleware with distributed computing ability.

JavaMavenApache License 2.0schedulerworkflow
powerjob.tech
7.8k1.4k
agronholm/apscheduler

Task scheduling library for Python

PythonPyPIMIT Licensecronscheduling
apscheduler.readthedocs.io
7.6k771
quartznet/quartznet

Quartz Enterprise Scheduler .NET

C#Apache License 2.0c-sharpdotnet
quartz-scheduler.net
7.1k1.7k
ouqiang/gocron

定时任务管理系统

GoGo ModulesMIT Licensecronscheduler
6.3k1.3k
xinliangnote/go-gin-api

基于 Gin 进行模块化设计的 API 框架,封装了常用功能,使用简单,致力于进行快速的业务研发。比如,支持 cors 跨域、jwt 签名验证、zap 日志收集、panic 异常捕获、trace 链路追踪、prometheus 监控指标、swagger 文档生成、viper 配置文件解析、gorm 数据库组件、gormgen 代码生成工具、graphql 查询语言、errno 统一定义错误码、gRPC 的使用、cron 定时任务 等等。

GoGo ModulesMIT Licensegolanggo
yuque.com/xinliangnote/go-gin-api/ngc3x5
6k1.1k
jhuckaby/Cronicle

A simple, distributed task scheduler and runner with a web based UI.

JavaScriptnpmOthercroncrontab
cronicle.net
5.8k499