CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-go-co-op-gocron-v2

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.

Overview
Eval results
Files

creating.mddocs/api/scheduler/

Creating Schedulers

How to create and configure schedulers with NewScheduler and all SchedulerOption functions.

NewScheduler

func NewScheduler(options ...SchedulerOption) (Scheduler, error)

Creates a new scheduler with optional configuration. Returns an error if any option is invalid.

s, err := gocron.NewScheduler()
if err != nil {
    return err
}
defer s.Shutdown()

Scheduler Options

WithLocation

func WithLocation(location *time.Location) SchedulerOption

Sets the default timezone for all jobs. Defaults to time.Local. Returns ErrWithLocationNil if nil.

Affects:

  • DailyJob, WeeklyJob, MonthlyJob schedules
  • CronJob schedules (unless overridden with TZ prefix)
  • Start/stop time calculations
loc, _ := time.LoadLocation("America/Chicago")
s, _ := gocron.NewScheduler(
    gocron.WithLocation(loc),
)

WithLogger

func WithLogger(logger Logger) SchedulerOption

Sets the logger for internal scheduler logging. Returns ErrWithLoggerNil if nil.

See Logger interface and Observability Guide.

s, _ := gocron.NewScheduler(
    gocron.WithLogger(gocron.NewLogger(gocron.LogLevelInfo)),
)

WithStopTimeout

func WithStopTimeout(timeout time.Duration) SchedulerOption

Sets the maximum time to wait for running jobs during StopJobs() or Shutdown(). Defaults to no timeout. Returns ErrWithStopTimeoutZeroOrNegative if ≤ 0.

s, _ := gocron.NewScheduler(
    gocron.WithStopTimeout(30*time.Second),
)

WithLimitConcurrentJobs

func WithLimitConcurrentJobs(limit uint, mode LimitMode) SchedulerOption

Limits the number of jobs running concurrently across the entire scheduler. Returns ErrWithLimitConcurrentJobsZero if limit is 0.

Modes:

  • LimitModeReschedule: Skip jobs if limit reached
  • LimitModeWait: Queue jobs if limit reached
s, _ := gocron.NewScheduler(
    gocron.WithLimitConcurrentJobs(3, gocron.LimitModeReschedule),
)

See Concurrency Guide.

WithGlobalJobOptions

func WithGlobalJobOptions(jobOptions ...JobOption) SchedulerOption

Applies job options to all jobs by default. Per-job options override global ones.

s, _ := gocron.NewScheduler(
    gocron.WithGlobalJobOptions(
        gocron.WithTags("production"),
        gocron.WithSingletonMode(gocron.LimitModeReschedule),
    ),
)

// All jobs get these options by default
j, _ := s.NewJob(
    gocron.DurationJob(time.Minute),
    gocron.NewTask(myFunc),
    gocron.WithTags("critical"), // adds to global "production" tag
)

WithMonitor

func WithMonitor(monitor Monitor) SchedulerOption

Sets a basic metrics collector. Returns ErrWithMonitorNil if nil.

See Monitor interface and Observability Guide.

s, _ := gocron.NewScheduler(
    gocron.WithMonitor(&myMonitor{}),
)

WithMonitorStatus

func WithMonitorStatus(monitor MonitorStatus) SchedulerOption

Sets a metrics collector that includes status and error information. Returns ErrWithMonitorNil if nil.

See MonitorStatus interface and Observability Guide.

s, _ := gocron.NewScheduler(
    gocron.WithMonitorStatus(&myMonitorStatus{}),
)

WithSchedulerMonitor

func WithSchedulerMonitor(monitor SchedulerMonitor) SchedulerOption

Sets a detailed lifecycle monitor. Returns ErrSchedulerMonitorNil if nil.

See SchedulerMonitor interface and Observability Guide.

s, _ := gocron.NewScheduler(
    gocron.WithSchedulerMonitor(&mySchedulerMonitor{}),
)

WithDistributedElector

func WithDistributedElector(elector Elector) SchedulerOption

Enables leader election for distributed deployments. Only the leader instance runs jobs. Returns ErrWithDistributedElectorNil if nil.

See Elector interface and Distributed Guide.

s, _ := gocron.NewScheduler(
    gocron.WithDistributedElector(&myElector{}),
)

WithDistributedLocker

func WithDistributedLocker(locker Locker) SchedulerOption

Enables per-job distributed locking. Returns ErrWithDistributedLockerNil if nil.

See Locker interface and Distributed Guide.

s, _ := gocron.NewScheduler(
    gocron.WithDistributedLocker(&myLocker{}),
)

WithClock

func WithClock(clock clockwork.Clock) SchedulerOption

Sets a custom clock implementation for testing. Returns ErrWithClockNil if nil.

import "github.com/jonboulle/clockwork"

fakeClock := clockwork.NewFakeClock()
s, _ := gocron.NewScheduler(
    gocron.WithClock(fakeClock),
)

// In tests
fakeClock.Advance(5 * time.Minute)

Usage Examples

Basic Setup

s, err := gocron.NewScheduler()
if err != nil {
    return err
}
defer s.Shutdown()

j, err := s.NewJob(
    gocron.DurationJob(time.Minute),
    gocron.NewTask(func() {
        fmt.Println("Running")
    }),
)

s.Start()
select {} // block

Full Configuration

loc, _ := time.LoadLocation("America/New_York")

s, err := gocron.NewScheduler(
    gocron.WithLocation(loc),
    gocron.WithLogger(gocron.NewLogger(gocron.LogLevelInfo)),
    gocron.WithStopTimeout(30*time.Second),
    gocron.WithLimitConcurrentJobs(5, gocron.LimitModeWait),
    gocron.WithGlobalJobOptions(
        gocron.WithTags("production"),
    ),
)

See Also

Install with Tessl CLI

npx tessl i tessl/golang-github-com-go-co-op-gocron-v2@2.19.1

docs

api

errors.md

quick-reference.md

tasks.md

index.md

tile.json