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

interfaces.mddocs/api/types/

Core Interfaces

Core types and interfaces in gocron v2.

Scheduler Interface

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.

Methods

  • NewJob: Registers a new job. Returns the job handle or an error if validation fails.
  • Update: Updates an existing job by ID. Replaces the job definition, task, and options.
  • RemoveJob: Removes a job by ID. Returns ErrJobNotFound if the job doesn't exist.
  • RemoveByTags: Removes all jobs that have all specified tags.
  • Jobs: Returns all currently registered jobs, sorted by ID.
  • Start: Starts the scheduler's main loop. Non-blocking.
  • StopJobs: Stops all jobs gracefully. Returns ErrStopJobsTimedOut if timeout exceeded.
  • Shutdown: Stops the scheduler and performs cleanup. Returns ErrStopSchedulerTimedOut if timeout exceeded.
  • JobsWaitingInQueue: Returns the number of jobs queued due to concurrency limits.

See Scheduler API for details.

Job Interface

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.

Methods

  • ID(): Returns the job's unique identifier. Stable across updates.
  • Name(): Returns the job's name (set via WithName or defaults to function name).
  • Tags(): Returns all tags assigned to the job.
  • LastRun(): Returns the time of the most recent execution. Returns ErrJobNotFound if removed.
  • NextRun(): Returns the next scheduled execution time. Returns ErrJobNotFound if removed.
  • NextRuns(count): Returns the next count scheduled execution times. Returns ErrJobNotFound if removed.
  • RunNow(): Triggers an immediate execution without affecting the schedule. Returns ErrJobRunNowFailed if scheduler is unreachable.

Usage

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()

JobDefinition Interface

type JobDefinition interface { /* opaque */ }

Defines when a job runs. Created by:

  • DurationJob
  • DurationRandomJob
  • CronJob
  • DailyJob
  • WeeklyJob
  • MonthlyJob
  • OneTimeJob

This is an opaque interface; you cannot implement it yourself. See Job Definitions for constructor functions.

Task Type

type Task func() task

Wraps a function to be executed by a job. Created with NewTask.

func NewTask(function any, parameters ...any) Task

The function must be a function (kind reflect.Func). Parameters are bound when creating the task.

Context Injection

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.

JobOption Type

type JobOption func(*internalJob, time.Time) error

Configures individual job behavior. Passed as variadic arguments to NewJob and Update.

Common options:

  • WithName - set job name
  • WithTags - assign tags
  • WithSingletonMode - prevent concurrent runs
  • WithLimitedRuns - limit execution count
  • WithEventListeners - attach callbacks

See Job Options for all options.

SchedulerOption Type

type SchedulerOption func(*scheduler) error

Configures scheduler-level behavior. Passed to NewScheduler.

Common options:

  • WithLocation - set timezone
  • WithLogger - configure logging
  • WithStopTimeout - graceful shutdown timeout
  • WithLimitConcurrentJobs - global concurrency limit
  • WithDistributedElector - leader election
  • WithDistributedLocker - distributed locking

See Scheduler API for all options.

Logger

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).

Built-In Logger

func NewLogger(level LogLevel) Logger

type LogLevel int

const (
    LogLevelError LogLevel = iota
    LogLevelWarn
    LogLevelInfo
    LogLevelDebug
)

Returns a logger writing to stdout.

Usage

func WithLogger(logger Logger) SchedulerOption

Returns ErrWithLoggerNil if nil.

Custom Logger Example

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.

LimitMode Type

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.

  • LimitModeReschedule: Skip the overlapping run and reschedule for the next time.
  • LimitModeWait: Queue the run and execute when the current run completes.

Used with:

  • WithSingletonMode(mode) - per-job concurrency control
  • WithLimitConcurrentJobs(limit, mode) - scheduler-level concurrency control

See Concurrency Options for details.

EventListener Type

type EventListener func(*internalJob) error

Event listener callback type. Attach to jobs via WithEventListeners.

Available listeners:

  • BeforeJobRuns - called before execution
  • BeforeJobRunsSkipIfBeforeFuncErrors - skip job if returns error
  • AfterJobRuns - called after successful execution
  • AfterJobRunsWithError - called after error
  • AfterJobRunsWithPanic - called after panic recovery
  • AfterLockError - called when lock acquisition fails

See Event Listeners for details.

Helper Types

AtTime and AtTimes

type AtTime interface { /* opaque */ }
type AtTimes interface { /* opaque */ }

func NewAtTime(hours, minutes, seconds uint) AtTime
func NewAtTimes(atTime AtTime, atTimes ...AtTime) AtTimes

Represent times-of-day for DailyJob, WeeklyJob, and MonthlyJob.

Weekdays

type Weekdays interface { /* opaque */ }

func NewWeekdays(weekday time.Weekday, weekdays ...time.Weekday) Weekdays

Represent days of the week for WeeklyJob.

DaysOfTheMonth

type DaysOfTheMonth interface { /* opaque */ }

func NewDaysOfTheMonth(day int, moreDays ...int) DaysOfTheMonth

Represent days of the month for MonthlyJob. Supports positive (1-31) and negative (-1 to -31) day numbers.

StartAtOption and StopAtOption

type StartAtOption func(*jobStartAtOptions) error
type StopAtOption func(*jobStopAtOptions) error

Control job start and stop times. See Timing Options.

OneTimeJobStartAtOption

type OneTimeJobStartAtOption func(*oneTimeJobDefinition) error

func OneTimeJobStartImmediately() OneTimeJobStartAtOption
func OneTimeJobStartDateTime(start time.Time) OneTimeJobStartAtOption
func OneTimeJobStartDateTimes(times ...time.Time) OneTimeJobStartAtOption

Control when OneTimeJob executes. See One-Time Jobs.

See Also

Install with Tessl CLI

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

docs

api

errors.md

quick-reference.md

tasks.md

index.md

tile.json