Top Related Projects
Quick Overview
go-quartz is a lightweight, zero-dependency scheduling library for Go applications. It provides a simple and flexible way to schedule and manage recurring tasks, jobs, and cron-like schedules in Go programs.
Pros
- Zero external dependencies, making it easy to integrate into existing projects
- Supports various scheduling patterns, including fixed-rate, fixed-delay, and cron expressions
- Thread-safe and designed for concurrent execution
- Lightweight and efficient, with minimal overhead
Cons
- Limited built-in persistence options compared to more comprehensive scheduling frameworks
- May require additional implementation for complex scheduling scenarios
- Documentation could be more extensive, especially for advanced use cases
- Relatively new project, which may mean less community support compared to more established libraries
Code Examples
- Creating a simple job:
type SimpleJob struct{}
func (j SimpleJob) Execute() {
fmt.Println("Simple job executed")
}
scheduler := quartz.NewStdScheduler()
scheduler.Start()
job := quartz.NewJobDetail(SimpleJob{}, "SimpleJob", "default")
trigger := quartz.NewSimpleTrigger("SimpleTrigger")
trigger.WithIntervalInSeconds(5)
scheduler.ScheduleJob(job, trigger)
- Using a cron trigger:
cronTrigger := quartz.NewCronTrigger("CronTrigger")
cronTrigger.WithCronExpression("0 0/5 * * * ?") // Every 5 minutes
scheduler.ScheduleJob(job, cronTrigger)
- Scheduling a job with a custom calendar:
calendar := quartz.NewHolidayCalendar()
calendar.AddExcludedDate(time.Date(2023, 12, 25, 0, 0, 0, 0, time.UTC))
trigger.SetCalendar(calendar)
scheduler.ScheduleJob(job, trigger)
Getting Started
To use go-quartz in your Go project, follow these steps:
-
Install the library:
go get github.com/reugn/go-quartz
-
Import the package in your Go code:
import "github.com/reugn/go-quartz"
-
Create a scheduler, define your jobs and triggers, and start scheduling:
scheduler := quartz.NewStdScheduler() scheduler.Start() // Define your jobs and triggers here // Use scheduler.ScheduleJob(job, trigger) to schedule jobs
Competitor Comparisons
a cron library for go
Pros of cron
- Simpler API and easier to use for basic scheduling needs
- Lightweight with minimal dependencies
- Well-established and widely adopted in the Go community
Cons of cron
- Limited support for advanced scheduling patterns
- Lacks built-in persistence and clustering capabilities
- Less flexible for complex job management scenarios
Code Comparison
cron:
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.Start()
go-quartz:
scheduler := quartz.NewStdScheduler()
job := quartz.NewFunctionJob(func(ctx context.Context) (int64, error) {
fmt.Println("Every hour on the half hour")
return 0, nil
})
trigger := quartz.NewCronTrigger("0 30 * * * *")
scheduler.ScheduleJob(job, trigger)
scheduler.Start(context.Background())
Key Differences
- go-quartz offers more advanced features like job chaining, listeners, and error handling
- cron uses a simpler string-based cron expression, while go-quartz provides more granular control over scheduling
- go-quartz supports context-based job execution, allowing for better cancellation and timeout handling
- cron is more suitable for simple scheduling tasks, while go-quartz is better for complex job management scenarios
Both libraries have their strengths, and the choice between them depends on the specific requirements of your project. cron is ideal for straightforward scheduling needs, while go-quartz offers more flexibility and advanced features for complex job management.
A Golang Job Scheduling Package.
Pros of gocron
- Simpler API and easier to use for basic scheduling tasks
- Supports both cron-like syntax and interval-based scheduling
- Lightweight with minimal dependencies
Cons of gocron
- Less feature-rich compared to go-quartz
- Limited support for advanced scheduling patterns
- Lacks built-in persistence and clustering capabilities
Code Comparison
gocron:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(task)
s.StartBlocking()
go-quartz:
scheduler := quartz.NewStdScheduler()
job := quartz.NewFunctionJob(task)
trigger := quartz.NewCronTrigger("0 30 10 * * ?")
scheduler.ScheduleJob(job, trigger)
scheduler.Start()
Both libraries provide scheduling capabilities for Go applications, but they differ in complexity and feature set. gocron offers a more straightforward approach for simple scheduling needs, while go-quartz provides a more robust and feature-rich solution inspired by the Java Quartz library.
gocron is ideal for projects requiring basic scheduling functionality with an easy-to-use API. However, for more complex scheduling requirements, advanced patterns, or enterprise-level features like persistence and clustering, go-quartz would be the better choice.
The code comparison demonstrates the difference in API design, with gocron using a more fluent interface and go-quartz adopting a more structured approach similar to its Java counterpart.
Framework for performing work asynchronously, outside of the request flow
Pros of jobrunner
- Simpler API with fewer concepts to learn
- Built-in web interface for job monitoring
- Easier to set up and use for basic scheduling needs
Cons of jobrunner
- Less flexible scheduling options compared to go-quartz
- Limited features for advanced use cases
- Less active development and community support
Code Comparison
jobrunner:
jobs.Every(5 * time.Minute, MyJob{})
jobs.Now(MyJob{})
go-quartz:
scheduler.ScheduleJob(job, trigger)
scheduler.Start()
Feature Comparison
go-quartz offers more advanced scheduling features, including:
- Cron-like expressions
- Calendar-based scheduling
- Misfire handling
jobrunner provides a simpler approach with:
- Interval-based scheduling
- One-time job execution
- Built-in web interface
Community and Maintenance
go-quartz:
- More recent updates
- Higher number of contributors
- More stars and forks on GitHub
jobrunner:
- Less frequent updates
- Fewer contributors
- Smaller community engagement
Conclusion
Choose jobrunner for simpler projects with basic scheduling needs and built-in monitoring. Opt for go-quartz when more advanced scheduling features and active community support are required.
A Distributed, Fault-Tolerant Cron-Style Job System.
Pros of cronsun
- Distributed system with master-worker architecture, suitable for large-scale deployments
- Web UI for job management and monitoring
- Built-in support for node grouping and failover
Cons of cronsun
- More complex setup and configuration compared to go-quartz
- Requires external dependencies like etcd for distributed coordination
- Steeper learning curve for users new to distributed systems
Code Comparison
cronsun job definition:
{
"name": "test job",
"command": "echo hello",
"schedule": "0 */5 * * * *",
"timezone": "Asia/Shanghai"
}
go-quartz job definition:
job := quartz.NewJobBuilder().
WithIdentity("test job").
Build()
trigger := quartz.NewCronTrigger("0 */5 * * * *")
scheduler.ScheduleJob(job, trigger)
cronsun focuses on distributed job scheduling with a more complex architecture, while go-quartz provides a simpler in-process scheduling solution. cronsun offers a web UI and built-in distributed features, making it suitable for larger deployments. go-quartz, on the other hand, is easier to integrate into existing Go applications and has a lower overhead for simpler use cases.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
go-quartz
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.
Top Related Projects
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot