A Golang job scheduling library that lets you run Go functions at pre-determined intervals using cron expressions, fixed durations, daily, weekly, monthly, or one-time schedules with support for distributed deployments.
Practical examples of job definitions and operations.
package main
import (
"fmt"
"time"
"github.com/go-co-op/gocron/v2"
)
func main() {
s, _ := gocron.NewScheduler()
defer s.Shutdown()
// Fixed interval
j1, _ := s.NewJob(
gocron.DurationJob(5*time.Minute),
gocron.NewTask(func() {
fmt.Println("Runs every 5 minutes")
}),
)
// Random interval (jittered)
j2, _ := s.NewJob(
gocron.DurationRandomJob(time.Minute, 5*time.Minute),
gocron.NewTask(func() {
fmt.Println("Runs at random interval between 1-5 minutes")
}),
)
s.Start()
select {}
}func main() {
s, _ := gocron.NewScheduler()
defer s.Shutdown()
// Every 5 minutes
j1, _ := s.NewJob(
gocron.CronJob("*/5 * * * *", false),
gocron.NewTask(func() {
fmt.Println("Every 5 minutes")
}),
)
// Daily at 9 AM
j2, _ := s.NewJob(
gocron.CronJob("0 9 * * *", false),
gocron.NewTask(func() {
fmt.Println("Daily at 9 AM")
}),
)
// With timezone
j3, _ := s.NewJob(
gocron.CronJob("TZ=America/New_York 0 9 * * *", false),
gocron.NewTask(func() {
fmt.Println("9 AM Eastern Time")
}),
)
s.Start()
select {}
}func main() {
s, _ := gocron.NewScheduler()
defer s.Shutdown()
// Daily at specific times
j1, _ := s.NewJob(
gocron.DailyJob(
1,
gocron.NewAtTimes(
gocron.NewAtTime(9, 0, 0),
gocron.NewAtTime(17, 0, 0),
),
),
gocron.NewTask(func() {
fmt.Println("Runs at 9 AM and 5 PM daily")
}),
)
// Weekly on Monday
j2, _ := s.NewJob(
gocron.WeeklyJob(
1,
gocron.NewWeekdays(time.Monday),
gocron.NewAtTimes(gocron.NewAtTime(9, 0, 0)),
),
gocron.NewTask(func() {
fmt.Println("Monday at 9 AM")
}),
)
// Monthly on 1st and 15th
j3, _ := s.NewJob(
gocron.MonthlyJob(
1,
gocron.NewDaysOfTheMonth(1, 15),
gocron.NewAtTimes(gocron.NewAtTime(0, 0, 0)),
),
gocron.NewTask(func() {
fmt.Println("1st and 15th at midnight")
}),
)
s.Start()
select {}
}func main() {
s, _ := gocron.NewScheduler()
defer s.Shutdown()
// Run once in 1 hour
j, _ := s.NewJob(
gocron.OneTimeJob(
gocron.OneTimeJobStartDateTime(
time.Now().Add(time.Hour),
),
),
gocron.NewTask(func() {
fmt.Println("Runs once")
}),
)
s.Start()
time.Sleep(2 * time.Hour) // Wait for completion
}Install with Tessl CLI
npx tessl i tessl/golang-github-com-go-co-op-gocron-v2docs
api
examples
guides