Task Scheduler in Go (Golang): cron, gocron and robfig/cron
A task scheduler is an indispensable tool for automating periodic operations in applications: from cache cleaning and sending notifications to launching background data processors. In the Go (Golang) ecosystem, there are several popular libraries for implementing cron-like behavior. In this article, we will look at three main approaches: the built-in cron package, the lightweight gocron, and the de facto standard robfig/cron.
1. Built-in cron package (experimental)
Starting with Go 1.19, the standard library introduced an experimental cron package in golang.org/x/exp/cron. It provides basic functionality for running tasks on a schedule. However, in practice it is rarely used due to limited functionality and lack of support for complex cron expressions (e.g., with seconds).
package main
import ( "context" "fmt" "golang.org/x/exp/cron" "time")
func main() { sched := cron.New() // Run every 10 seconds sched.Add("*/10 * * * * *", func() { fmt.Println("Task executed:", time.Now()) }) sched.Start() time.Sleep(30 * time.Second) sched.Stop()}2. robfig/cron library — the gold standard
The github.com/robfig/cron/v3 library is the most popular and mature implementation of a task scheduler in Go. It supports:
- Standard cron expressions (5 fields) with an optional seconds field
- Predefined schedules:
@yearly,@monthly,@weekly,@daily,@hourly - Intervals:
@every 5m(every 5 minutes) - Time zones
- Panic handling via a Recovery logger
- Flexible logging system through the
Loggerinterface
Installation
go get github.com/robfig/cron/v3Basic example
package main
import ( "fmt" "github.com/robfig/cron/v3" "time")
func main() { c := cron.New(cron.WithSeconds()) // Enable seconds support
// Every minute at 30 seconds c.AddFunc("30 * * * * *", func() { fmt.Println("Every minute at 30 seconds:", time.Now().Format("15:04:05")) })
// Every day at 8:00 AM c.AddFunc("0 0 8 * * *", func() { fmt.Println("Daily at 8:00") })
// Every 2 hours c.AddFunc("@every 2h", func() { fmt.Println("Every 2 hours") })
// Monday at 9:30 c.AddFunc("30 9 * * 1", func() { fmt.Println("Every Monday at 9:30") })
c.Start() defer c.Stop()
// Wait 1 minute to see execution time.Sleep(70 * time.Second)}Cron expression syntax in robfig/cron
A standard expression consists of 5 fields (minutes, hours, day of month, month, day of week). When the cron.WithSeconds() option is enabled, a sixth field — seconds (0-59) — is added.
*— any value*/5— every 5 units1,15,30— specific values1-10— rangeL— last (e.g., last day of the month)
3. gocron library — simplicity and readability
github.com/go-co-op/gocron offers a higher-level, fluent interface for creating schedules. It is ideal if you do not need complex cron expressions and simple intervals are sufficient.
Installation
go get github.com/go-co-op/gocron/v2Usage example
package main
import ( "fmt"