• Stars
    star
    1,635
  • Rank 28,601 (Top 0.6 %)
  • Language
    Go
  • License
    MIT License
  • Created over 5 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Minimalist and zero-dependency scheduling library for Go

go-quartz

Build PkgGoDev Go Report Card codecov

A minimalistic and zero-dependency scheduling library for Go.

About

Inspired by the Quartz Java scheduler.

Library building blocks

Scheduler interface

type Scheduler interface {
	// Start starts the scheduler. The scheduler will run until
	// the Stop method is called or the context is canceled. Use
	// the Wait method to block until all running jobs have completed.
	Start(context.Context)

	// IsStarted determines whether the scheduler has been started.
	IsStarted() bool

	// ScheduleJob schedules a job using a specified trigger.
	ScheduleJob(jobDetail *JobDetail, trigger Trigger) error

	// GetJobKeys returns the keys of scheduled jobs.
	// For a job key to be returned, the job must satisfy all of the
	// matchers specified.
	// Given no matchers, it returns the keys of all scheduled jobs.
	GetJobKeys(...Matcher[ScheduledJob]) ([]*JobKey, error)

	// GetScheduledJob returns the scheduled job with the specified key.
	GetScheduledJob(jobKey *JobKey) (ScheduledJob, error)

	// DeleteJob removes the job with the specified key from the
	// scheduler's execution queue.
	DeleteJob(jobKey *JobKey) error

	// PauseJob suspends the job with the specified key from being
	// executed by the scheduler.
	PauseJob(jobKey *JobKey) error

	// ResumeJob restarts the suspended job with the specified key.
	ResumeJob(jobKey *JobKey) error

	// Clear removes all of the scheduled jobs.
	Clear() error

	// Wait blocks until the scheduler stops running and all jobs
	// have returned. Wait will return when the context passed to
	// it has expired. Until the context passed to start is
	// cancelled or Stop is called directly.
	Wait(context.Context)

	// Stop shutdowns the scheduler.
	Stop()
}

Implemented Schedulers

  • StdScheduler

Trigger interface

type Trigger interface {
	// NextFireTime returns the next time at which the Trigger is scheduled to fire.
	NextFireTime(prev int64) (int64, error)

	// Description returns the description of the Trigger.
	Description() string
}

Implemented Triggers

  • CronTrigger
  • SimpleTrigger
  • RunOnceTrigger

Job interface

Any type that implements it can be scheduled.

type Job interface {
	// Execute is called by a Scheduler when the Trigger associated with this job fires.
	Execute(context.Context) error

	// Description returns the description of the Job.
	Description() string
}

Several common Job implementations can be found in the job package.

Cron expression format

Field Name Mandatory Allowed Values Allowed Special Characters
Seconds YES 0-59 , - * /
Minutes YES 0-59 , - * /
Hours YES 0-23 , - * /
Day of month YES 1-31 , - * ? /
Month YES 1-12 or JAN-DEC , - * /
Day of week YES 1-7 or SUN-SAT , - * ? /
Year NO empty, 1970- , - * /

Distributed mode

The scheduler can use its own implementation of quartz.JobQueue to allow state sharing.
An example implementation of the job queue using the file system as a persistence layer can be found here.

Logger

To set a custom logger, use the logger.SetDefault function.
The argument must implement the logger.Logger interface.

The following example shows how to disable library logs.

import "github.com/reugn/go-quartz/logger"

logger.SetDefault(logger.NewSimpleLogger(nil, logger.LevelOff))

Examples

package main

import (
	"context"
	"net/http"
	"time"

	"github.com/reugn/go-quartz/job"
	"github.com/reugn/go-quartz/quartz"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// create scheduler
	sched := quartz.NewStdScheduler()

	// async start scheduler
	sched.Start(ctx)

	// create jobs
	cronTrigger, _ := quartz.NewCronTrigger("1/5 * * * * *")
	shellJob := job.NewShellJob("ls -la")

	request, _ := http.NewRequest(http.MethodGet, "https://worldtimeapi.org/api/timezone/utc", nil)
	curlJob := job.NewCurlJob(request)

	functionJob := job.NewFunctionJob(func(_ context.Context) (int, error) { return 42, nil })

	// register jobs to scheduler
	sched.ScheduleJob(quartz.NewJobDetail(shellJob, quartz.NewJobKey("shellJob")),
		cronTrigger)
	sched.ScheduleJob(quartz.NewJobDetail(curlJob, quartz.NewJobKey("curlJob")),
		quartz.NewSimpleTrigger(time.Second*7))
	sched.ScheduleJob(quartz.NewJobDetail(functionJob, quartz.NewJobKey("functionJob")),
		quartz.NewSimpleTrigger(time.Second*5))

	// stop scheduler
	sched.Stop()

	// wait for all workers to exit
	sched.Wait(ctx)
}

More code samples can be found in the examples directory.

License

Licensed under the MIT License.

More Repositories

1

go-streams

A lightweight stream processing library for Go
Go
1,734
star
2

dev-tools

Widely used software developer tools in a single application
Java
282
star
3

wifiqr

Create a QR code with your Wi-Fi login details
Go
250
star
4

async

Synchronization and asynchronous computation package for Go
Go
181
star
5

equalizer

A set of performant rate limiters for Go
Go
77
star
6

auth-server

Simple authentication and authorization service
Go
69
star
7

tpack

Pack a Go workflow/function as a Unix-style pipeline command
Go
55
star
8

rspark

β–β–‚β–†β–‡β–β–„β–ˆβ– Sparklines for Rust apps
Rust
49
star
9

sketch

An image manipulation library for Kotlin
Kotlin
45
star
10

kotlin-backoff

An exponential backoff library for Kotlin
Kotlin
40
star
11

gemini-cli

A command-line interface (CLI) for Google Gemini
Go
36
star
12

fsweeper

A file management automation tool
Go
30
star
13

scala-statecharts

Scala statecharts collection (FSM, UML)
Scala
12
star
14

dynamic

A Scala library that allows copying a case class using a dynamic property name
Scala
11
star
15

aerospike-client-scala

Idiomatic and reactive Scala client for Aerospike database
Scala
10
star
16

memento

Kafka messages non-blocking reprocessor and delayed producer service
Scala
9
star
17

kafka-aerospike-state-store

Kafka Streams custom persistent StateStore backed by Aerospike
Java
9
star
18

gravity

An efficient Java substring search library
Java
8
star
19

scalikejackson

Lightweight Scala JSON library
Scala
7
star
20

github-action-aerospike

GitHub Action to set up an Aerospike database
Shell
6
star
21

aerospike-client-kotlin

Aerospike Client for Kotlin
Kotlin
4
star
22

aerospike-cli

A command line utility to query the Aerospike database using SQL
Kotlin
4
star
23

micrometer-registry-aerospike

A Micrometer MeterRegistry for Aerospike
Java
3
star
24

github-action-pulsar

GitHub Action to set up Apache Pulsar
Shell
3
star
25

pyloc

Python implementation of tool for counting lines of code
Python
2
star
26

pkgslog

A package level structured log/slog handler for Go
Go
2
star
27

cloud-storage-benchmark

A CLI tool to evaluate performance of various cloud storage providers
Go
1
star