Use robfig/cron by creating a cron instance, adding jobs with standard cron expressions or custom parsers, and then running the scheduler in a separate goroutine. The library handles parsing, scheduling, and execution automatically, so you just need to define the job function and the schedule string.
Here is a basic example using the standard cron format (minute, hour, day of month, month, day of week):
package main
import (
"fmt"
"log"
"time"
"github.com/robfig/cron/v3"
)
func main() {
c := cron.New()
// Schedule a job to run every 5 minutes
_, err := c.AddFunc("*/5 * * * *", func() {
fmt.Println("Running every 5 minutes:", time.Now())
})
if err != nil {
log.Fatal(err)
}
// Schedule a job to run once at 9:30 AM every day
_, err = c.AddFunc("30 9 * * *", func() {
fmt.Println("Daily task at 9:30 AM")
})
if err != nil {
log.Fatal(err)
}
// Start the scheduler in a goroutine
c.Start()
// Keep the program running (in a real app, you'd handle signals here)
select {}
}
If you need more control, such as pausing the scheduler or retrieving job IDs for removal, use the cron.New constructor with options and the AddJob method instead of AddFunc:
package main
import (
"fmt"
"log"
"time"
"github.com/robfig/cron/v3"
)
func main() {
// Create a new cron with standard parsing
c := cron.New()
// Add a job that returns an ID for later management
id, err := c.AddJob("*/10 * * * *", cron.FuncJob(func() {
fmt.Println("Job running every 10 minutes")
}))
if err != nil {
log.Fatal(err)
}
c.Start()
// Simulate work, then stop the specific job after 30 seconds
time.Sleep(30 * time.Second)
c.Remove(id)
fmt.Println("Job removed")
// Stop the entire scheduler when done
c.Stop()
}
Remember that robfig/cron defaults to the standard 5-field cron format. If you need to support seconds or different time zones, you must pass a custom cron.Parser to the constructor. For example, cron.New(cron.WithParser(cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor))) enables 6-field expressions including seconds. Always ensure your scheduler runs in its own goroutine and that you handle the Stop() call gracefully during application shutdown to prevent goroutine leaks.