gocron
Easy and fluent Go cron scheduling. This is a fork from https://github.com/jasonlvhit/gocron
Top Related Projects
Quick Overview
go-co-op/gocron is a Go library for scheduling and running recurring tasks. It provides a simple and flexible way to create and manage cron jobs in Go applications, allowing developers to easily schedule functions to run at specific intervals or times.
Pros
- Easy to use with a clean and intuitive API
- Supports various scheduling options (e.g., intervals, specific times, weekdays)
- Thread-safe and concurrent execution of jobs
- Extensible with custom job storage options
Cons
- Limited built-in persistence options for job schedules
- May not be suitable for distributed systems without additional implementation
- Lacks some advanced features found in more complex job scheduling systems
Code Examples
- Basic job scheduling:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Hour().Do(func() {
fmt.Println("Task runs every hour")
})
s.StartBlocking()
- Scheduling a job at a specific time:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(func() {
fmt.Println("Task runs daily at 10:30 UTC")
})
s.StartAsync()
- Using weekdays for scheduling:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Monday().At("18:00").Do(func() {
fmt.Println("Task runs every Monday at 18:00 UTC")
})
s.StartAsync()
Getting Started
To use go-co-op/gocron in your Go project, follow these steps:
-
Install the library:
go get github.com/go-co-op/gocron
-
Import the library in your Go code:
import ( "github.com/go-co-op/gocron" "time" )
-
Create a scheduler and add jobs:
s := gocron.NewScheduler(time.UTC) s.Every(5).Seconds().Do(func() { fmt.Println("Task running every 5 seconds") }) s.StartBlocking()
This example creates a scheduler that runs a task every 5 seconds and blocks the main thread. You can customize the scheduling and execution behavior based on your specific requirements.
Competitor Comparisons
a cron library for go
Pros of cron
- Lightweight and simple to use
- Well-established and widely adopted in the Go community
- Supports standard cron syntax for job scheduling
Cons of cron
- Lacks advanced features like job chaining or error handling
- No built-in persistence or distributed scheduling support
- Less active development and fewer updates compared to gocron
Code Comparison
cron:
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.Start()
gocron:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Hour().At("30:00").Do(func() { fmt.Println("Every hour on the half hour") })
s.StartAsync()
Both libraries provide similar basic functionality for scheduling jobs. However, gocron offers a more fluent and readable API, while cron uses the traditional cron syntax.
gocron provides additional features like job chaining, error handling, and more flexible scheduling options. It also has better support for concurrent execution and offers methods for managing running jobs.
cron is a good choice for simple scheduling needs and projects that require a lightweight solution. gocron is more suitable for complex scheduling requirements and projects that need advanced features or better job management capabilities.
A Golang Job Scheduling Package.
Pros of gocron (jasonlvhit)
- Simpler API with fewer dependencies
- Lightweight and easy to integrate into existing projects
- Supports both cron-like syntax and interval-based scheduling
Cons of gocron (jasonlvhit)
- Less actively maintained (last commit in 2021)
- Fewer advanced features compared to go-co-op/gocron
- Limited concurrency control options
Code Comparison
gocron (jasonlvhit):
s := gocron.NewScheduler()
s.Every(1).Day().At("10:30").Do(task)
s.Start()
gocron (go-co-op):
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(task)
s.StartAsync()
The basic usage is similar, but go-co-op/gocron offers more flexibility with timezone handling and asynchronous execution. go-co-op/gocron also provides additional features like:
- Job chaining
- Customizable job storage
- Better error handling and logging
- More granular scheduling options
While jasonlvhit/gocron is simpler and may be sufficient for basic use cases, go-co-op/gocron offers a more robust and feature-rich solution for complex scheduling needs in Go applications.
Minimalist and zero-dependency scheduling library for Go
Pros of go-quartz
- More flexible job scheduling with support for complex cron expressions
- Built-in clustering and distributed execution capabilities
- Better performance for high-volume scheduling scenarios
Cons of go-quartz
- Steeper learning curve due to more complex API
- Less active community and fewer contributors compared to gocron
- Fewer built-in features for common use cases
Code Comparison
gocron example:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(task)
s.StartBlocking()
go-quartz example:
scheduler := quartz.NewStdScheduler()
job := quartz.NewJobDetail(myJob, "group1", "job1")
trigger := quartz.NewCronTrigger("0 30 10 * * ?")
scheduler.ScheduleJob(job, trigger)
scheduler.Start()
Both libraries offer job scheduling capabilities, but go-quartz provides more advanced features for complex scheduling needs and distributed environments. gocron, on the other hand, offers a simpler API and is more suitable for straightforward scheduling tasks. The choice between the two depends on the specific requirements of your project, such as the complexity of scheduling needs and the desired level of control over job execution.
Framework for performing work asynchronously, outside of the request flow
Pros of jobrunner
- Simpler API with fewer methods, making it easier to learn and use for basic scheduling needs
- Lightweight implementation with minimal dependencies
- Supports job chaining, allowing for sequential execution of tasks
Cons of jobrunner
- Less actively maintained, with fewer recent updates and contributions
- Limited feature set compared to gocron, lacking advanced scheduling options
- Smaller community and fewer resources available for support and troubleshooting
Code Comparison
jobrunner:
jobs.Every(5 * time.Minute, MyJob{})
jobs.Every(3 * time.Hour, AnotherJob{})
jobs.Start()
gocron:
s := gocron.NewScheduler(time.UTC)
s.Every(5).Minutes().Do(myJob)
s.Every(3).Hours().Do(anotherJob)
s.StartAsync()
Both libraries offer straightforward ways to schedule jobs, but gocron provides more flexibility in defining intervals and offers additional scheduling options. jobrunner uses a struct-based approach for job definitions, while gocron allows for direct function calls. gocron's API is more expressive, allowing for chaining of methods to define job schedules.
A Distributed, Fault-Tolerant Cron-Style Job System.
Pros of cronsun
- Distributed system architecture, allowing for better scalability and fault tolerance
- Web-based UI for job management and monitoring
- Supports multiple node execution for load balancing
Cons of cronsun
- More complex setup and configuration due to distributed nature
- Requires additional infrastructure (etcd) for coordination
- Less actively maintained compared to gocron
Code Comparison
gocron:
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(task)
s.StartBlocking()
cronsun:
node := cronsun.NewNode(cfg)
node.Run()
Summary
cronsun is a distributed job scheduling system with a web UI, offering better scalability for large-scale applications. However, it comes with increased complexity and infrastructure requirements. gocron, on the other hand, is a simpler, in-process scheduler that's easier to integrate into existing Go applications but may not scale as well for distributed environments. The choice between the two depends on the specific needs of your project, such as scale, infrastructure, and management requirements.
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
gocron: A Golang Job Scheduling Package
gocron is a job scheduling package which lets you run Go functions at pre-determined intervals.
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()
if err != nil {
// handle error
}
}
Examples
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).
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.
- 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.
- Listeners: Can be added to a job, with event listeners, or all jobs across the scheduler to listen for job events and 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 theWithGlobalJobOptions
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.
- Monitor:
- MonitorStatus (includes status and error (if any) of the Job)
A monitor can be used to collect metrics for each job from a scheduler.
- Implementations: go-co-op monitors (don't see what you need? request on slack to get a repo created to contribute it!)
Testing
The gocron library is set up to enable testing.
- Mocks are provided in the mock package using gomock.
- Time can be mocked by passing in a FakeClock to WithClock - see the example on WithClock.
Supporters
We appreciate the support for free and open source software!
This project is supported by:
Star History
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