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.
Core types and interfaces in gocron v2.
type Scheduler interface {
NewJob(JobDefinition, Task, ...JobOption) (Job, error)
Update(uuid.UUID, JobDefinition, Task, ...JobOption) (Job, error)
RemoveJob(uuid.UUID) error
RemoveByTags(...string)
Jobs() []Job
Start()
StopJobs() error
Shutdown() error
JobsWaitingInQueue() int
}The main scheduler interface. Create with NewScheduler.
ErrJobNotFound if the job doesn't exist.ErrStopJobsTimedOut if timeout exceeded.ErrStopSchedulerTimedOut if timeout exceeded.See Scheduler API for details.
type Job interface {
ID() uuid.UUID
Name() string
Tags() []string
LastRun() (time.Time, error)
NextRun() (time.Time, error)
NextRuns(count int) ([]time.Time, error)
RunNow() error
}Represents a scheduled job. Returned by Scheduler.NewJob and Scheduler.Update.
WithName or defaults to function name).ErrJobNotFound if removed.ErrJobNotFound if removed.count scheduled execution times. Returns ErrJobNotFound if removed.ErrJobRunNowFailed if scheduler is unreachable.j, _ := s.NewJob(
gocron.DurationJob(time.Minute),
gocron.NewTask(myFunc),
gocron.WithName("my-job"),
)
id := j.ID()
name := j.Name()
tags := j.Tags()
lastRun, err := j.LastRun()
nextRun, err := j.NextRun()
nextFive, err := j.NextRuns(5)
// Trigger immediately
err = j.RunNow()type JobDefinition interface { /* opaque */ }Defines when a job runs. Created by:
DurationJobDurationRandomJobCronJobDailyJobWeeklyJobMonthlyJobOneTimeJobThis is an opaque interface; you cannot implement it yourself. See Job Definitions for constructor functions.
type Task func() taskWraps a function to be executed by a job. Created with NewTask.
func NewTask(function any, parameters ...any) TaskThe function must be a function (kind reflect.Func). Parameters are bound when creating the task.
If the function's first parameter is context.Context, gocron automatically injects it. Do NOT pass it as a parameter.
// CORRECT: context auto-injected
task := gocron.NewTask(func(ctx context.Context) {
doWork()
})
// CORRECT: context + parameters
task := gocron.NewTask(func(ctx context.Context, msg string, n int) {
fmt.Println(msg, n)
}, "hello", 42)
// INCORRECT: don't pass context as parameter
// task := gocron.NewTask(func(ctx context.Context) { ... }, myContext)See Task API for details.
type JobOption func(*internalJob, time.Time) errorConfigures individual job behavior. Passed as variadic arguments to NewJob and Update.
Common options:
WithName - set job nameWithTags - assign tagsWithSingletonMode - prevent concurrent runsWithLimitedRuns - limit execution countWithEventListeners - attach callbacksSee Job Options for all options.
type SchedulerOption func(*scheduler) errorConfigures scheduler-level behavior. Passed to NewScheduler.
Common options:
WithLocation - set timezoneWithLogger - configure loggingWithStopTimeout - graceful shutdown timeoutWithLimitConcurrentJobs - global concurrency limitWithDistributedElector - leader electionWithDistributedLocker - distributed lockingSee Scheduler API for all options.
type Logger interface {
Debug(msg string, args ...any)
Error(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
}Logging interface for scheduler internals. Modeled after slog (key-value pairs in args).
func NewLogger(level LogLevel) Logger
type LogLevel int
const (
LogLevelError LogLevel = iota
LogLevelWarn
LogLevelInfo
LogLevelDebug
)Returns a logger writing to stdout.
func WithLogger(logger Logger) SchedulerOptionReturns ErrWithLoggerNil if nil.
type slogLogger struct {
l *slog.Logger
}
func (l *slogLogger) Debug(msg string, args ...any) { l.l.Debug(msg, args...) }
func (l *slogLogger) Error(msg string, args ...any) { l.l.Error(msg, args...) }
func (l *slogLogger) Info(msg string, args ...any) { l.l.Info(msg, args...) }
func (l *slogLogger) Warn(msg string, args ...any) { l.l.Warn(msg, args...) }
s, _ := gocron.NewScheduler(
gocron.WithLogger(&slogLogger{l: slog.Default()}),
)See Observability Guide for more examples.
type LimitMode int
const (
LimitModeReschedule LimitMode = 1 // Skip overlapping runs
LimitModeWait LimitMode = 2 // Queue overlapping runs
)Controls behavior when jobs overlap due to concurrency limits.
Used with:
WithSingletonMode(mode) - per-job concurrency controlWithLimitConcurrentJobs(limit, mode) - scheduler-level concurrency controlSee Concurrency Options for details.
type EventListener func(*internalJob) errorEvent listener callback type. Attach to jobs via WithEventListeners.
Available listeners:
BeforeJobRuns - called before executionBeforeJobRunsSkipIfBeforeFuncErrors - skip job if returns errorAfterJobRuns - called after successful executionAfterJobRunsWithError - called after errorAfterJobRunsWithPanic - called after panic recoveryAfterLockError - called when lock acquisition failsSee Event Listeners for details.
type AtTime interface { /* opaque */ }
type AtTimes interface { /* opaque */ }
func NewAtTime(hours, minutes, seconds uint) AtTime
func NewAtTimes(atTime AtTime, atTimes ...AtTime) AtTimesRepresent times-of-day for DailyJob, WeeklyJob, and MonthlyJob.
type Weekdays interface { /* opaque */ }
func NewWeekdays(weekday time.Weekday, weekdays ...time.Weekday) WeekdaysRepresent days of the week for WeeklyJob.
type DaysOfTheMonth interface { /* opaque */ }
func NewDaysOfTheMonth(day int, moreDays ...int) DaysOfTheMonthRepresent days of the month for MonthlyJob. Supports positive (1-31) and negative (-1 to -31) day numbers.
type StartAtOption func(*jobStartAtOptions) error
type StopAtOption func(*jobStopAtOptions) errorControl job start and stop times. See Timing Options.
type OneTimeJobStartAtOption func(*oneTimeJobDefinition) error
func OneTimeJobStartImmediately() OneTimeJobStartAtOption
func OneTimeJobStartDateTime(start time.Time) OneTimeJobStartAtOption
func OneTimeJobStartDateTimes(times ...time.Time) OneTimeJobStartAtOptionControl when OneTimeJob executes. See One-Time Jobs.
Install with Tessl CLI
npx tessl i tessl/golang-github-com-go-co-op-gocron-v2docs
api
examples
guides