scheduler

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 19 Imported by: 0

README

scheduler logo

A fluent, Laravel-inspired scheduler for Go that wraps gocron with expressive APIs for defining, filtering, and controlling scheduled jobs.

Go Reference Go Test Go version Latest tag Tests Go Report Card

Features

  • Fluent, chainable API for intervals, cron strings, and calendar helpers (daily/weekly/monthly).
  • Overlap protection with optional distributed locking plus per-job tags and metadata.
  • Filters (weekdays/weekends/time windows) and hooks (before/after/success/failure) keep jobs predictable.
  • Command execution helper for running CLI tasks with background mode and env-aware tagging.
  • Auto-generated, compile-tested examples ensure docs and behavior stay in sync.

Why scheduler?

Go has excellent low-level scheduling libraries, but defining real-world schedules often turns into a maze of cron strings, conditionals, and glue code.

scheduler provides a Laravel-style fluent API on top of gocron that lets you describe when, how, and under what conditions a job should run - without hiding what’s actually happening.

Everything remains explicit, testable, and inspectable, while staying pleasant to read and maintain.

Quick Start

Basic

s := scheduler.New()
defer s.Stop()

s.EveryMinute().Name("cleanup").Do(func() { runCleanup() }) // run in-process cleanup every minute
s.DailyAt("09:00").Weekdays().Name("reports:morning").Do(func() { sendMorningReport() }) // weekdays at 09:00
s.Cron("0 0 * * *").Command("reports:purge", "--force") // run app subcommand nightly
s.Cron("*/15 * * * *").Exec("/usr/bin/env", "echo", "heartbeat") // run external executable every 15 minutes
s.EveryFiveMinutes().WithoutOverlapping().Name("sync:inventory").Do(func() { syncInventory() }) // prevent overlapping runs
s.Cron("0 * * * *").When(func() bool { return isPrimaryNode() }).Name("rebalance").Do(func() { rebalance() }) // run only when condition passes

Advanced (kitchen sink)

s := scheduler.New()
defer s.Stop()

s.
	Name("reports:generate").
	Timezone("America/New_York").
	Weekdays().
	Between("09:00", "17:00").
	WithoutOverlapping().
	Before(func() { markJobStart("reports:generate") }).
	OnSuccess(func() { notifySuccess("reports:generate") }).
	OnFailure(func() { notifyFailure("reports:generate") }).
	DailyAt("10:30").
	Do(func() { generateReports() })

s.
	Name("reconcile:daily").
	RunInBackground().
	Cron("0 3 * * *").
	Command("billing:reconcile", "--retry=3")

List jobs as an ASCII table

package main

import (
	"github.com/goforj/scheduler"
)

func main() {
	s := scheduler.New()
	defer s.Stop()

	s.EveryMinute().Name("cleanup").Do(func() {}) // run cleanup every minute
	s.DailyAt("10:30").Weekdays().Name("reports:generate").Do(func() {}) // run reports on weekdays at 10:30
	s.Cron("0 0 * * *").Command("reports:purge", "--force") // run app subcommand nightly at midnight

	s.PrintJobsList()
}

Example output:

+------------------------------------------------------------------------------------------------------------------------+
| Scheduler Jobs › (3)                                                                                                  |
+------------------+----------+----------------+-----------------------+----------------------+--------------------------+
| Name             | Type     | Schedule       | Handler               | Next Run             | Tags                     |
+------------------+----------+----------------+-----------------------+----------------------+--------------------------+
| cleanup          | function | every 1m       | main.main (anon func) | in 1m Mar 3 2:16AM  | env=local                |
| reports:generate | function | cron 30 10 * * * | main.main (anon func) | in 8h Mar 3 10:30AM | env=local                |
| reports:purge    | command  | cron 0 0 * * * | -                     | in 21h Mar 4 12:00AM | env=local, args="--force" |
+------------------+----------+----------------+-----------------------+----------------------+--------------------------+

Runnable examples

Every function has a corresponding runnable example under ./examples.

These examples are generated directly from the documentation blocks of each function, ensuring the docs and code never drift. These are the same examples you see here in the README and GoDoc.

An automated test executes every example to verify it builds and runs successfully.

This guarantees all examples are valid, up-to-date, and remain functional as the API evolves.

API Index

Group Functions
Adapters Lock Run Unlock
Calendar Daily DailyAt DaysOfMonth LastDayOfMonth Monthly MonthlyOn Quarterly QuarterlyOn TwiceDaily TwiceDailyAt TwiceMonthly Weekly WeeklyOn Yearly YearlyOn
Commands Command Exec
Concurrency WithoutOverlapping WithoutOverlappingWithLocker
Configuration Timezone WithCommandRunner WithNowFunc
Construction New NewWithError
Diagnostics CronExpr Error Job Jobs PrintJobsList
Execution RunInBackground
Filters Between Days Environments Fridays Mondays Saturdays Skip Sundays Thursdays Tuesdays UnlessBetween Wednesdays Weekdays Weekends When
Hooks After Before OnFailure OnSuccess
Interop GocronScheduler
Intervals Every EveryDuration EveryFifteenMinutes EveryFifteenSeconds EveryFiveMinutes EveryFiveSeconds EveryFourHours EveryFourMinutes EveryMinute EveryOddHour EverySecond EverySixHours EveryTenMinutes EveryTenSeconds EveryThirtyMinutes EveryThirtySeconds EveryThreeHours EveryThreeMinutes EveryTwentySeconds EveryTwoHours EveryTwoMinutes EveryTwoSeconds Hourly HourlyAt Hours Minutes Seconds
Lifecycle Shutdown Start Stop
Locking NewCacheLocker NewRedisLocker
Metadata JobMetadata JobsInfo Name
Runtime control IsJobPaused IsPausedAll Observe PauseAll PauseJob ResumeAll ResumeJob
State management RetainState
Triggers Cron Do

Adapters

Lock

Lock invokes the underlying function.

client := redis.NewClient(&redis.Options{})
locker := scheduler.NewRedisLocker(client, 10*time.Minute)
lock, _ := locker.Lock(context.Background(), "job")
_ = lock.Unlock(context.Background())

Run

Run executes the underlying function.

runner := scheduler.CommandRunnerFunc(func(ctx context.Context, exe string, args []string) error {
	return nil
})
_ = runner.Run(context.Background(), "echo", []string{"hi"})

Unlock

Unlock invokes the underlying function.

lock := scheduler.LockFunc(func(context.Context) error { return nil })
_ = lock.Unlock(context.Background())

Calendar

Daily

Daily schedules the job to run once per day at midnight.

scheduler.New().Daily()

DailyAt

DailyAt schedules the job to run daily at a specific time (e.g., "13:00").

scheduler.New().DailyAt("12:30")

DaysOfMonth

DaysOfMonth schedules the job to run on specific days of the month at a given time.

scheduler.New().DaysOfMonth([]int{5, 20}, "07:15")

LastDayOfMonth

LastDayOfMonth schedules the job to run on the last day of each month at a specific time.

scheduler.New().LastDayOfMonth("23:30")

Monthly

Monthly schedules the job to run on the first day of each month at midnight.

scheduler.New().Monthly()

MonthlyOn

MonthlyOn schedules the job to run on a specific day of the month at a given time.

scheduler.New().MonthlyOn(15, "09:30")

Quarterly

Quarterly schedules the job to run on the first day of each quarter at midnight.

scheduler.New().Quarterly()

QuarterlyOn

QuarterlyOn schedules the job to run on a specific day of each quarter at a given time.

scheduler.New().QuarterlyOn(3, "12:00")

TwiceDaily

TwiceDaily schedules the job to run daily at two specified hours (e.g., 1 and 13).

scheduler.New().TwiceDaily(1, 13)

TwiceDailyAt

TwiceDailyAt schedules the job to run daily at two specified times (e.g., 1:15 and 13:15).

scheduler.New().TwiceDailyAt(1, 13, 15)

TwiceMonthly

TwiceMonthly schedules the job to run on two specific days of the month at the given time.

scheduler.New().TwiceMonthly(1, 15, "10:00")

Weekly

Weekly schedules the job to run once per week on Sunday at midnight.

scheduler.New().Weekly()

WeeklyOn

WeeklyOn schedules the job to run weekly on a specific day of the week and time. Day uses 0 = Sunday through 6 = Saturday.

scheduler.New().WeeklyOn(1, "8:00")

Yearly

Yearly schedules the job to run on January 1st every year at midnight.

scheduler.New().Yearly()

YearlyOn

YearlyOn schedules the job to run every year on a specific month, day, and time.

scheduler.New().YearlyOn(12, 25, "06:45")

Commands

Command

Command executes the current binary with the given subcommand and variadic args. It does not run arbitrary system executables; use Exec for that.

scheduler.New().Cron("0 0 * * *").Command("jobs:purge", "--force")

Exec

Exec runs an external executable with variadic args.

scheduler.New().Cron("0 0 * * *").Exec("/usr/bin/env", "echo", "hello")

Concurrency

WithoutOverlapping

WithoutOverlapping ensures the job does not run concurrently.

scheduler.New().
	WithoutOverlapping().
	EveryFiveSeconds().
	Do(func() { time.Sleep(7 * time.Second) })

WithoutOverlappingWithLocker

WithoutOverlappingWithLocker ensures the job does not run concurrently across distributed systems using the provided locker.

locker := scheduler.LockerFunc(func(ctx context.Context, key string) (gocron.Lock, error) {
	return scheduler.LockFunc(func(context.Context) error { return nil }), nil
})

scheduler.New().
	WithoutOverlappingWithLocker(locker).
	EveryMinute().
	Do(func() {})

Configuration

Timezone

Timezone sets a timezone string for the job (not currently applied to gocron Scheduler).

scheduler.New().Timezone("America/New_York").Daily()

WithCommandRunner

WithCommandRunner overrides command execution (default: exec.CommandContext).

runner := scheduler.CommandRunnerFunc(func(_ context.Context, exe string, args []string) error {
	_ = exe
	_ = args
	return nil
})

builder := scheduler.New().WithCommandRunner(runner)
_ = builder

WithNowFunc

WithNowFunc overrides current time (default: time.Now). Useful for tests.

fixed := func() time.Time { return time.Unix(0, 0) }
scheduler.New().WithNowFunc(fixed)

Construction

New

New creates and starts a scheduler facade. It panics only if gocron scheduler construction fails.

s := scheduler.New()
defer s.Stop()
s.Every(15).Seconds().Do(func() {})

NewWithError

NewWithError creates and starts a scheduler facade and returns setup errors.

s, err := scheduler.NewWithError()
if err != nil {
	panic(err)
}
defer s.Stop()

Diagnostics

CronExpr

CronExpr returns the cron expression string configured for this job.

builder := scheduler.New().Cron("0 9 * * *")
fmt.Println(builder.CronExpr())
// Output: 0 9 * * *

Error

Error returns the error if any occurred during job scheduling.

builder := scheduler.New().DailyAt("bad")
fmt.Println(builder.Error())
// Output: invalid DailyAt time format: invalid time format (expected HH:MM): "bad"

Job

Job returns the last scheduled gocron.Job instance, if available.

b := scheduler.New().EverySecond().Do(func() {})
fmt.Println(b.Job() != nil)
// Output: true

Jobs

Jobs returns scheduled jobs from the underlying scheduler.

PrintJobsList

PrintJobsList renders and prints the scheduler job table to stdout.

s := scheduler.New()
defer s.Stop()
s.EverySecond().Name("heartbeat").Do(func() {})
s.PrintJobsList()
// Output:
// +------------------------------------------------------------------------------------------+
// | Scheduler Jobs › (1)
// +-----------+----------+----------+-----------------------+--------------------+-----------+
// | Name      | Type     | Schedule | Handler               | Next Run           | Tags      |
// +-----------+----------+----------+-----------------------+--------------------+-----------+
// | heartbeat | function | every 1s | main.main (anon func) | in 1s Mar 3 2:15AM | env=local |
// +-----------+----------+----------+-----------------------+--------------------+-----------+

Execution

RunInBackground

RunInBackground runs command/exec tasks in a goroutine.

scheduler.New().RunInBackground().Command("noop")

Filters

Between

Between limits the job to run between the provided HH:MM times (inclusive).

scheduler.New().Between("09:00", "17:00").EveryMinute()

Days

Days limits the job to a specific set of weekdays.

scheduler.New().Days(time.Monday, time.Wednesday, time.Friday).DailyAt("07:00")

Environments

Environments restricts job registration to specific environment names (e.g. "production", "staging").

scheduler.New().Environments("production").Daily()

Fridays

Fridays limits the job to Fridays.

scheduler.New().Fridays().DailyAt("09:00")

Mondays

Mondays limits the job to Mondays.

scheduler.New().Mondays().DailyAt("09:00")

Saturdays

Saturdays limits the job to Saturdays.

scheduler.New().Saturdays().DailyAt("09:00")

Skip

Skip prevents scheduling the job if the provided condition returns true.

enabled := false
scheduler.New().Skip(func() bool { return !enabled }).Daily()

Sundays

Sundays limits the job to Sundays.

scheduler.New().Sundays().DailyAt("09:00")

Thursdays

Thursdays limits the job to Thursdays.

scheduler.New().Thursdays().DailyAt("09:00")

Tuesdays

Tuesdays limits the job to Tuesdays.

scheduler.New().Tuesdays().DailyAt("09:00")

UnlessBetween

UnlessBetween prevents the job from running between the provided HH:MM times.

scheduler.New().UnlessBetween("22:00", "06:00").EveryMinute()

Wednesdays

Wednesdays limits the job to Wednesdays.

scheduler.New().Wednesdays().DailyAt("09:00")

Weekdays

Weekdays limits the job to run only on weekdays (Mon-Fri).

scheduler.New().Weekdays().DailyAt("09:00")

Weekends

Weekends limits the job to run only on weekends (Sat-Sun).

scheduler.New().Weekends().DailyAt("10:00")

When

When only schedules the job if the provided condition returns true.

flag := true
scheduler.New().When(func() bool { return flag }).Daily()

Hooks

After

After sets a hook to run after task execution.

scheduler.New().After(func() {}).Daily()

Before

Before sets a hook to run before task execution.

scheduler.New().Before(func() {}).Daily()

OnFailure

OnFailure sets a hook to run after failed task execution.

scheduler.New().OnFailure(func() {}).Daily()

OnSuccess

OnSuccess sets a hook to run after successful task execution.

scheduler.New().OnSuccess(func() {}).Daily()

Interop

GocronScheduler

GocronScheduler returns the underlying gocron scheduler for advanced integration. Prefer the fluent scheduler API for typical use-cases.

Intervals

Every

Every schedules a job to run every X seconds, minutes, or hours.

scheduler.New().Every(10).Minutes()

EveryDuration

EveryDuration schedules a duration-based interval job builder.

EveryFifteenMinutes

EveryFifteenMinutes schedules the job to run every 15 minutes.

scheduler.New().EveryFifteenMinutes().Do(func() {})

EveryFifteenSeconds

EveryFifteenSeconds schedules the job to run every 15 seconds.

scheduler.New().EveryFifteenSeconds().Do(func() {})

EveryFiveMinutes

EveryFiveMinutes schedules the job to run every 5 minutes.

scheduler.New().EveryFiveMinutes().Do(func() {})

EveryFiveSeconds

EveryFiveSeconds schedules the job to run every 5 seconds.

scheduler.New().EveryFiveSeconds().Do(func() {})

EveryFourHours

EveryFourHours schedules the job to run every four hours at the specified minute.

scheduler.New().EveryFourHours(25)

EveryFourMinutes

EveryFourMinutes schedules the job to run every 4 minutes.

scheduler.New().EveryFourMinutes().Do(func() {})

EveryMinute

EveryMinute schedules the job to run every 1 minute.

scheduler.New().EveryMinute().Do(func() {})

EveryOddHour

EveryOddHour schedules the job to run every odd-numbered hour at the specified minute.

scheduler.New().EveryOddHour(10)

EverySecond

EverySecond schedules the job to run every 1 second.

scheduler.New().EverySecond().Do(func() {})

EverySixHours

EverySixHours schedules the job to run every six hours at the specified minute.

scheduler.New().EverySixHours(30)

EveryTenMinutes

EveryTenMinutes schedules the job to run every 10 minutes.

scheduler.New().EveryTenMinutes().Do(func() {})

EveryTenSeconds

EveryTenSeconds schedules the job to run every 10 seconds.

scheduler.New().EveryTenSeconds().Do(func() {})

EveryThirtyMinutes

EveryThirtyMinutes schedules the job to run every 30 minutes.

scheduler.New().EveryThirtyMinutes().Do(func() {})

EveryThirtySeconds

EveryThirtySeconds schedules the job to run every 30 seconds.

scheduler.New().EveryThirtySeconds().Do(func() {})

EveryThreeHours

EveryThreeHours schedules the job to run every three hours at the specified minute.

scheduler.New().EveryThreeHours(20)

EveryThreeMinutes

EveryThreeMinutes schedules the job to run every 3 minutes.

scheduler.New().EveryThreeMinutes().Do(func() {})

EveryTwentySeconds

EveryTwentySeconds schedules the job to run every 20 seconds.

scheduler.New().EveryTwentySeconds().Do(func() {})

EveryTwoHours

EveryTwoHours schedules the job to run every two hours at the specified minute.

scheduler.New().EveryTwoHours(15)

EveryTwoMinutes

EveryTwoMinutes schedules the job to run every 2 minutes.

scheduler.New().EveryTwoMinutes().Do(func() {})

EveryTwoSeconds

EveryTwoSeconds schedules the job to run every 2 seconds.

scheduler.New().EveryTwoSeconds().Do(func() {})

Hourly

Hourly schedules the job to run every hour.

scheduler.New().Hourly().Do(func() {})

HourlyAt

HourlyAt schedules the job to run every hour at the specified minute.

scheduler.New().HourlyAt(5)

Hours

Hours schedules the job to run every X hours.

scheduler.New().Every(6).Hours()

Minutes

Minutes schedules the job to run every X minutes.

scheduler.New().Every(15).Minutes()

Seconds

Seconds schedules the job to run every X seconds.

scheduler.New().Every(3).Seconds().Do(func() {})

Lifecycle

Shutdown

Shutdown gracefully shuts down the underlying scheduler.

s := scheduler.New()
_ = s.Shutdown()

Start

Start starts the underlying scheduler.

s := scheduler.New()
s.Start()

Stop

Stop gracefully shuts down the scheduler.

s := scheduler.New()
_ = s.Stop()

Locking

NewCacheLocker

NewCacheLocker creates a CacheLocker with a cache lock client and TTL. The ttl is a lease duration: when it expires, another worker may acquire the same lock key. For long-running jobs, choose ttl >= worst-case runtime plus a safety buffer. If your runtime can exceed ttl, prefer a renewing/heartbeat lock strategy.

Example: use an in-memory cache driver

client := cache.NewCache(cache.NewMemoryStore(context.Background()))
locker := scheduler.NewCacheLocker(client, 10*time.Minute)
_, _ = locker.Lock(context.Background(), "job")

Example: use the Redis cache driver

redisStore := rediscache.New(rediscache.Config{
	Addr: "127.0.0.1:6379",
})
redisClient := cache.NewCache(redisStore)
redisLocker := scheduler.NewCacheLocker(redisClient, 10*time.Minute)
_, _ = redisLocker.Lock(context.Background(), "job")

NewRedisLocker

NewRedisLocker creates a RedisLocker with a client and TTL. The ttl is a lease duration: when it expires, another worker may acquire the same lock key. For long-running jobs, choose ttl >= worst-case runtime plus a safety buffer. If your runtime can exceed ttl, prefer a renewing/heartbeat lock strategy.

client := redis.NewClient(&redis.Options{}) // replace with your client
locker := scheduler.NewRedisLocker(client, 10*time.Minute)
_, _ = locker.Lock(context.Background(), "job")

Metadata

JobMetadata

JobMetadata returns a copy of the tracked job metadata keyed by job ID.

b := scheduler.New().EverySecond().Do(func() {})
for id, meta := range b.JobMetadata() {
	_ = id
	_ = meta.Name
}

JobsInfo

JobsInfo returns a stable, sorted snapshot of all known job metadata. This is a facade-friendly list form of JobMetadata including paused state.

s := scheduler.New()
s.EverySecond().Name("heartbeat").Do(func() {})
for _, job := range s.JobsInfo() {
	_ = job.ID
	_ = job.Name
	_ = job.Paused
}

Name

Name sets an explicit job name.

scheduler.New().Name("cache:refresh").HourlyAt(15)

Runtime control

IsJobPaused

IsJobPaused reports whether a specific job is paused.

IsPausedAll

IsPausedAll reports whether global pause is enabled.

Observe

Observe registers a lifecycle observer for all scheduled jobs. Events are emitted consistently across Do, Command, and Exec jobs.

s := scheduler.New()
s.Observe(scheduler.JobObserverFunc(func(event scheduler.JobEvent) {
	if event.Type == scheduler.JobSkipped && event.Reason == "paused" {
		fmt.Println("skipped: paused")
	}
}))

PauseAll

PauseAll pauses execution for all scheduled jobs without removing them. This is universal across Do, Command, and Exec jobs. RunNow calls are skipped while pause is active.

s := scheduler.New()
_ = s.PauseAll()

PauseJob

PauseJob pauses execution for a specific scheduled job. RunNow calls for that job are skipped while paused.

s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func() {})
_ = s.PauseJob(b.Job().ID())

ResumeAll

ResumeAll resumes execution for all paused jobs.

s := scheduler.New()
_ = s.ResumeAll()

ResumeJob

ResumeJob resumes a paused job by ID.

s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func() {})
_ = s.ResumeJob(b.Job().ID())

State management

RetainState

RetainState allows the job to retain its state after execution.

builder := scheduler.New().EverySecond().RetainState()
builder.Do(func() {})
builder.Do(func() {})

Triggers

Cron

Cron sets the cron expression for the job.

builder := scheduler.New().Cron("15 3 * * *")
fmt.Println(builder.CronExpr())
// Output: 15 3 * * *

Do

Do schedules the job with the provided task function.

scheduler.New().Name("cleanup").Cron("0 0 * * *").Do(func() {})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheLocker added in v1.1.0

type CacheLocker struct {
	// contains filtered or unexported fields
}

CacheLocker adapts a cache lock API to gocron.Locker. It uses a single key per job and auto-expires after ttl.

func NewCacheLocker added in v1.1.0

func NewCacheLocker(client cache.LockAPI, ttl time.Duration) *CacheLocker

NewCacheLocker creates a CacheLocker with a cache lock client and TTL. The ttl is a lease duration: when it expires, another worker may acquire the same lock key. For long-running jobs, choose ttl >= worst-case runtime plus a safety buffer. If your runtime can exceed ttl, prefer a renewing/heartbeat lock strategy. @group Locking

Example: use an in-memory cache driver

client := cache.NewCache(cache.NewMemoryStore(context.Background()))
locker := scheduler.NewCacheLocker(client, 10*time.Minute)
_, _ = locker.Lock(context.Background(), "job")

Example: use the Redis cache driver

redisStore := rediscache.New(rediscache.Config{
	Addr: "127.0.0.1:6379",
})
redisClient := cache.NewCache(redisStore)
redisLocker := scheduler.NewCacheLocker(redisClient, 10*time.Minute)
_, _ = redisLocker.Lock(context.Background(), "job")

func (*CacheLocker) Lock added in v1.1.0

func (l *CacheLocker) Lock(ctx context.Context, key string) (gocron.Lock, error)

Lock obtains a lock for the job name using the cache lock API. @group Locking

type CommandRunner

type CommandRunner interface {
	Run(ctx context.Context, exe string, args []string) error
}

CommandRunner abstracts exec so callers/tests can override.

type CommandRunnerFunc

type CommandRunnerFunc func(ctx context.Context, exe string, args []string) error

CommandRunnerFunc adapts a function to satisfy CommandRunner. @group Adapters

Example: wrap a function as a runner

runner := scheduler.CommandRunnerFunc(func(ctx context.Context, exe string, args []string) error {
	return nil
})
_ = runner.Run(context.Background(), "/bin/true", []string{})

func (CommandRunnerFunc) Run

func (f CommandRunnerFunc) Run(ctx context.Context, exe string, args []string) error

Run executes the underlying function. @group Adapters

Example: execute the wrapped function

runner := scheduler.CommandRunnerFunc(func(ctx context.Context, exe string, args []string) error {
	return nil
})
_ = runner.Run(context.Background(), "echo", []string{"hi"})

type FluentEvery

type FluentEvery struct {
	// contains filtered or unexported fields
}

FluentEvery is a wrapper for scheduling jobs at regular intervals.

func (*FluentEvery) Hours

func (fe *FluentEvery) Hours() *JobBuilder

Hours schedules the job to run every X hours. @group Intervals

Example: build an hourly cadence

scheduler.New().Every(6).Hours()

func (*FluentEvery) Minutes

func (fe *FluentEvery) Minutes() *JobBuilder

Minutes schedules the job to run every X minutes. @group Intervals

Example: chain a minute-based interval

scheduler.New().Every(15).Minutes()

func (*FluentEvery) Seconds

func (fe *FluentEvery) Seconds() *JobBuilder

Seconds schedules the job to run every X seconds. @group Intervals

Example: run a task every few seconds

scheduler.New().Every(3).Seconds().Do(func() {})

type JobBuilder

type JobBuilder struct {
	// contains filtered or unexported fields
}

JobBuilder is a wrapper around gocron.Job that provides a fluent interface for scheduling jobs.

func NewJobBuilder

func NewJobBuilder(s SchedulerAdapter) *JobBuilder

func (*JobBuilder) After

func (j *JobBuilder) After(fn func()) *JobBuilder

After sets a hook to run after task execution. @group Hooks

Example: add an after hook

scheduler.New().After(func() {}).Daily()

func (*JobBuilder) Before

func (j *JobBuilder) Before(fn func()) *JobBuilder

Before sets a hook to run before task execution. @group Hooks

Example: add a before hook

scheduler.New().Before(func() {}).Daily()

func (*JobBuilder) Between

func (j *JobBuilder) Between(start, end string) *JobBuilder

Between limits the job to run between the provided HH:MM times (inclusive). @group Filters

Example: allow execution during business hours

scheduler.New().Between("09:00", "17:00").EveryMinute()

func (*JobBuilder) Command

func (j *JobBuilder) Command(subcommand string, args ...string) *JobBuilder

Command executes the current binary with the given subcommand and variadic args. It does not run arbitrary system executables; use Exec for that. @group Commands

Example: run a CLI subcommand on schedule

scheduler.New().Cron("0 0 * * *").Command("jobs:purge", "--force")

func (*JobBuilder) Cron

func (j *JobBuilder) Cron(expr string) *JobBuilder

Cron sets the cron expression for the job. @group Triggers

Example: configure a cron expression

builder := scheduler.New().Cron("15 3 * * *")
fmt.Println(builder.CronExpr())
// Output: 15 3 * * *

func (*JobBuilder) CronExpr

func (j *JobBuilder) CronExpr() string

CronExpr returns the cron expression string configured for this job. @group Diagnostics

Example: inspect the stored cron expression

builder := scheduler.New().Cron("0 9 * * *")
fmt.Println(builder.CronExpr())
// Output: 0 9 * * *

func (*JobBuilder) Daily

func (j *JobBuilder) Daily() *JobBuilder

Daily schedules the job to run once per day at midnight. @group Calendar

Example: nightly task

scheduler.New().Daily()

func (*JobBuilder) DailyAt

func (j *JobBuilder) DailyAt(hm string) *JobBuilder

DailyAt schedules the job to run daily at a specific time (e.g., "13:00"). @group Calendar

Example: run at lunch time daily

scheduler.New().DailyAt("12:30")

func (*JobBuilder) Days

func (j *JobBuilder) Days(days ...time.Weekday) *JobBuilder

Days limits the job to a specific set of weekdays. @group Filters

Example: pick custom weekdays

scheduler.New().Days(time.Monday, time.Wednesday, time.Friday).DailyAt("07:00")

func (*JobBuilder) DaysOfMonth

func (j *JobBuilder) DaysOfMonth(days []int, hm string) *JobBuilder

DaysOfMonth schedules the job to run on specific days of the month at a given time. @group Calendar

Example: run on the 5th and 20th of each month

scheduler.New().DaysOfMonth([]int{5, 20}, "07:15")

func (*JobBuilder) Do

func (j *JobBuilder) Do(task func()) *JobBuilder

Do schedules the job with the provided task function. @group Triggers

Example: create a named cron job

scheduler.New().Name("cleanup").Cron("0 0 * * *").Do(func() {})

func (*JobBuilder) Environments

func (j *JobBuilder) Environments(envs ...string) *JobBuilder

Environments restricts job registration to specific environment names (e.g. "production", "staging"). @group Filters

Example: only register in production

scheduler.New().Environments("production").Daily()

func (*JobBuilder) Error

func (j *JobBuilder) Error() error

Error returns the error if any occurred during job scheduling. @group Diagnostics

Example: validate a malformed schedule

builder := scheduler.New().DailyAt("bad")
fmt.Println(builder.Error())
// Output: invalid DailyAt time format: invalid time format (expected HH:MM): "bad"

func (*JobBuilder) Every

func (j *JobBuilder) Every(duration int) *FluentEvery

Every schedules a job to run every X seconds, minutes, or hours. @group Intervals

Example: fluently choose an interval

scheduler.New().Every(10).Minutes()

func (*JobBuilder) EveryFifteenMinutes

func (j *JobBuilder) EveryFifteenMinutes() *JobBuilder

EveryFifteenMinutes schedules the job to run every 15 minutes. @group Intervals

Example: run every fifteen minutes

scheduler.New().EveryFifteenMinutes().Do(func() {})

func (*JobBuilder) EveryFifteenSeconds

func (j *JobBuilder) EveryFifteenSeconds() *JobBuilder

EveryFifteenSeconds schedules the job to run every 15 seconds. @group Intervals

Example: run at fifteen-second cadence

scheduler.New().EveryFifteenSeconds().Do(func() {})

func (*JobBuilder) EveryFiveMinutes

func (j *JobBuilder) EveryFiveMinutes() *JobBuilder

EveryFiveMinutes schedules the job to run every 5 minutes. @group Intervals

Example: run every five minutes

scheduler.New().EveryFiveMinutes().Do(func() {})

func (*JobBuilder) EveryFiveSeconds

func (j *JobBuilder) EveryFiveSeconds() *JobBuilder

EveryFiveSeconds schedules the job to run every 5 seconds. @group Intervals

Example: space out work every five seconds

scheduler.New().EveryFiveSeconds().Do(func() {})

func (*JobBuilder) EveryFourHours

func (j *JobBuilder) EveryFourHours(minute int) *JobBuilder

EveryFourHours schedules the job to run every four hours at the specified minute. @group Intervals

Example: run every four hours

scheduler.New().EveryFourHours(25)

func (*JobBuilder) EveryFourMinutes

func (j *JobBuilder) EveryFourMinutes() *JobBuilder

EveryFourMinutes schedules the job to run every 4 minutes. @group Intervals

Example: run every four minutes

scheduler.New().EveryFourMinutes().Do(func() {})

func (*JobBuilder) EveryMinute

func (j *JobBuilder) EveryMinute() *JobBuilder

EveryMinute schedules the job to run every 1 minute. @group Intervals

Example: run a task each minute

scheduler.New().EveryMinute().Do(func() {})

func (*JobBuilder) EveryOddHour

func (j *JobBuilder) EveryOddHour(minute int) *JobBuilder

EveryOddHour schedules the job to run every odd-numbered hour at the specified minute. @group Intervals

Example: run every odd hour

scheduler.New().EveryOddHour(10)

func (*JobBuilder) EverySecond

func (j *JobBuilder) EverySecond() *JobBuilder

EverySecond schedules the job to run every 1 second. @group Intervals

Example: heartbeat job each second

scheduler.New().EverySecond().Do(func() {})

func (*JobBuilder) EverySixHours

func (j *JobBuilder) EverySixHours(minute int) *JobBuilder

EverySixHours schedules the job to run every six hours at the specified minute. @group Intervals

Example: run every six hours

scheduler.New().EverySixHours(30)

func (*JobBuilder) EveryTenMinutes

func (j *JobBuilder) EveryTenMinutes() *JobBuilder

EveryTenMinutes schedules the job to run every 10 minutes. @group Intervals

Example: run every ten minutes

scheduler.New().EveryTenMinutes().Do(func() {})

func (*JobBuilder) EveryTenSeconds

func (j *JobBuilder) EveryTenSeconds() *JobBuilder

EveryTenSeconds schedules the job to run every 10 seconds. @group Intervals

Example: poll every ten seconds

scheduler.New().EveryTenSeconds().Do(func() {})

func (*JobBuilder) EveryThirtyMinutes

func (j *JobBuilder) EveryThirtyMinutes() *JobBuilder

EveryThirtyMinutes schedules the job to run every 30 minutes. @group Intervals

Example: run every thirty minutes

scheduler.New().EveryThirtyMinutes().Do(func() {})

func (*JobBuilder) EveryThirtySeconds

func (j *JobBuilder) EveryThirtySeconds() *JobBuilder

EveryThirtySeconds schedules the job to run every 30 seconds. @group Intervals

Example: execute every thirty seconds

scheduler.New().EveryThirtySeconds().Do(func() {})

func (*JobBuilder) EveryThreeHours

func (j *JobBuilder) EveryThreeHours(minute int) *JobBuilder

EveryThreeHours schedules the job to run every three hours at the specified minute. @group Intervals

Example: run every three hours

scheduler.New().EveryThreeHours(20)

func (*JobBuilder) EveryThreeMinutes

func (j *JobBuilder) EveryThreeMinutes() *JobBuilder

EveryThreeMinutes schedules the job to run every 3 minutes. @group Intervals

Example: run every three minutes

scheduler.New().EveryThreeMinutes().Do(func() {})

func (*JobBuilder) EveryTwentySeconds

func (j *JobBuilder) EveryTwentySeconds() *JobBuilder

EveryTwentySeconds schedules the job to run every 20 seconds. @group Intervals

Example: run once every twenty seconds

scheduler.New().EveryTwentySeconds().Do(func() {})

func (*JobBuilder) EveryTwoHours

func (j *JobBuilder) EveryTwoHours(minute int) *JobBuilder

EveryTwoHours schedules the job to run every two hours at the specified minute. @group Intervals

Example: run every two hours

scheduler.New().EveryTwoHours(15)

func (*JobBuilder) EveryTwoMinutes

func (j *JobBuilder) EveryTwoMinutes() *JobBuilder

EveryTwoMinutes schedules the job to run every 2 minutes. @group Intervals

Example: job that runs every two minutes

scheduler.New().EveryTwoMinutes().Do(func() {})

func (*JobBuilder) EveryTwoSeconds

func (j *JobBuilder) EveryTwoSeconds() *JobBuilder

EveryTwoSeconds schedules the job to run every 2 seconds. @group Intervals

Example: throttle a task to two seconds

scheduler.New().EveryTwoSeconds().Do(func() {})

func (*JobBuilder) Exec added in v1.2.0

func (j *JobBuilder) Exec(executable string, args ...string) *JobBuilder

Exec runs an external executable with variadic args. @group Commands

Example: run a system executable on schedule

scheduler.New().Cron("0 0 * * *").Exec("/usr/bin/env", "echo", "hello")

func (*JobBuilder) Fridays

func (j *JobBuilder) Fridays() *JobBuilder

Fridays limits the job to Fridays. @group Filters

Example: run only on Fridays

scheduler.New().Fridays().DailyAt("09:00")

func (*JobBuilder) Hourly

func (j *JobBuilder) Hourly() *JobBuilder

Hourly schedules the job to run every hour. @group Intervals

Example: run something hourly

scheduler.New().Hourly().Do(func() {})

func (*JobBuilder) HourlyAt

func (j *JobBuilder) HourlyAt(minute int) *JobBuilder

HourlyAt schedules the job to run every hour at the specified minute. @group Intervals

Example: run at the 5th minute of each hour

scheduler.New().HourlyAt(5)

func (*JobBuilder) IsJobPaused added in v1.3.0

func (j *JobBuilder) IsJobPaused(id uuid.UUID) bool

IsJobPaused reports whether a specific job is paused. @group Runtime control

func (*JobBuilder) IsPausedAll added in v1.3.0

func (j *JobBuilder) IsPausedAll() bool

IsPausedAll reports whether global pause is enabled. @group Runtime control

func (*JobBuilder) Job

func (j *JobBuilder) Job() gocron.Job

Job returns the last scheduled gocron.Job instance, if available. @group Diagnostics

Example: capture the last job handle

b := scheduler.New().EverySecond().Do(func() {})
fmt.Println(b.Job() != nil)
// Output: true

func (*JobBuilder) JobMetadata

func (j *JobBuilder) JobMetadata() map[uuid.UUID]JobMetadata

JobMetadata returns a copy of the tracked job metadata keyed by job ID. @group Metadata

Example: inspect scheduled jobs

b := scheduler.New().EverySecond().Do(func() {})
for id, meta := range b.JobMetadata() {
	_ = id
	_ = meta.Name
}

func (*JobBuilder) JobsInfo added in v1.3.0

func (j *JobBuilder) JobsInfo() []JobMetadata

JobsInfo returns a stable, sorted snapshot of all known job metadata. This is a facade-friendly list form of JobMetadata including paused state. @group Metadata

Example: iterate jobs for UI rendering

s := scheduler.New()
s.EverySecond().Name("heartbeat").Do(func() {})
for _, job := range s.JobsInfo() {
	_ = job.ID
	_ = job.Name
	_ = job.Paused
}

func (*JobBuilder) LastDayOfMonth

func (j *JobBuilder) LastDayOfMonth(hm string) *JobBuilder

LastDayOfMonth schedules the job to run on the last day of each month at a specific time. @group Calendar

Example: run on the last day of the month

scheduler.New().LastDayOfMonth("23:30")

func (*JobBuilder) Mondays

func (j *JobBuilder) Mondays() *JobBuilder

Mondays limits the job to Mondays. @group Filters

Example: run only on Mondays

scheduler.New().Mondays().DailyAt("09:00")

func (*JobBuilder) Monthly

func (j *JobBuilder) Monthly() *JobBuilder

Monthly schedules the job to run on the first day of each month at midnight. @group Calendar

Example: first-of-month billing

scheduler.New().Monthly()

func (*JobBuilder) MonthlyOn

func (j *JobBuilder) MonthlyOn(day int, hm string) *JobBuilder

MonthlyOn schedules the job to run on a specific day of the month at a given time. @group Calendar

Example: run on the 15th of each month

scheduler.New().MonthlyOn(15, "09:30")

func (*JobBuilder) Name

func (j *JobBuilder) Name(name string) *JobBuilder

Name sets an explicit job name. @group Metadata

Example: label a job for logging

scheduler.New().Name("cache:refresh").HourlyAt(15)

func (*JobBuilder) Observe added in v1.3.0

func (j *JobBuilder) Observe(observer JobObserver) *JobBuilder

Observe registers a lifecycle observer for all scheduled jobs. Events are emitted consistently across Do, Command, and Exec jobs. @group Runtime control

Example: observe paused-skip events

s := scheduler.New()
s.Observe(scheduler.JobObserverFunc(func(event scheduler.JobEvent) {
	if event.Type == scheduler.JobSkipped && event.Reason == "paused" {
		fmt.Println("skipped: paused")
	}
}))

func (*JobBuilder) OnFailure

func (j *JobBuilder) OnFailure(fn func()) *JobBuilder

OnFailure sets a hook to run after failed task execution. @group Hooks

Example: record failures

scheduler.New().OnFailure(func() {}).Daily()

func (*JobBuilder) OnSuccess

func (j *JobBuilder) OnSuccess(fn func()) *JobBuilder

OnSuccess sets a hook to run after successful task execution. @group Hooks

Example: record success

scheduler.New().OnSuccess(func() {}).Daily()

func (*JobBuilder) PauseAll added in v1.3.0

func (j *JobBuilder) PauseAll() error

PauseAll pauses execution for all scheduled jobs without removing them. This is universal across Do, Command, and Exec jobs. RunNow calls are skipped while pause is active. @group Runtime control

Example: pause all jobs

s := scheduler.New()
_ = s.PauseAll()

func (*JobBuilder) PauseJob added in v1.3.0

func (j *JobBuilder) PauseJob(id uuid.UUID) error

PauseJob pauses execution for a specific scheduled job. RunNow calls for that job are skipped while paused. @group Runtime control

Example: pause one job by ID

s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func() {})
_ = s.PauseJob(b.Job().ID())

func (*JobBuilder) PrintJobsList

func (j *JobBuilder) PrintJobsList()

PrintJobsList renders and prints the scheduler job table to stdout. @group Diagnostics

Example: print current jobs

s := scheduler.New()
defer s.Stop()
s.EverySecond().Name("heartbeat").Do(func() {})
s.PrintJobsList()
// Output:
// +------------------------------------------------------------------------------------------+
// | Scheduler Jobs › (1)
// +-----------+----------+----------+-----------------------+--------------------+-----------+
// | Name      | Type     | Schedule | Handler               | Next Run           | Tags      |
// +-----------+----------+----------+-----------------------+--------------------+-----------+
// | heartbeat | function | every 1s | main.main (anon func) | in 1s Mar 3 2:15AM | env=local |
// +-----------+----------+----------+-----------------------+--------------------+-----------+

func (*JobBuilder) Quarterly

func (j *JobBuilder) Quarterly() *JobBuilder

Quarterly schedules the job to run on the first day of each quarter at midnight. @group Calendar

Example: quarterly trigger

scheduler.New().Quarterly()

func (*JobBuilder) QuarterlyOn

func (j *JobBuilder) QuarterlyOn(day int, hm string) *JobBuilder

QuarterlyOn schedules the job to run on a specific day of each quarter at a given time. @group Calendar

Example: quarterly on a specific day

scheduler.New().QuarterlyOn(3, "12:00")

func (*JobBuilder) ResumeAll added in v1.3.0

func (j *JobBuilder) ResumeAll() error

ResumeAll resumes execution for all paused jobs. @group Runtime control

Example: resume all jobs

s := scheduler.New()
_ = s.ResumeAll()

func (*JobBuilder) ResumeJob added in v1.3.0

func (j *JobBuilder) ResumeJob(id uuid.UUID) error

ResumeJob resumes a paused job by ID. @group Runtime control

Example: resume one job by ID

s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func() {})
_ = s.ResumeJob(b.Job().ID())

func (*JobBuilder) RetainState

func (j *JobBuilder) RetainState() *JobBuilder

RetainState allows the job to retain its state after execution. @group State management

Example: reuse interval configuration for multiple jobs

builder := scheduler.New().EverySecond().RetainState()
builder.Do(func() {})
builder.Do(func() {})

func (*JobBuilder) RunInBackground

func (j *JobBuilder) RunInBackground() *JobBuilder

RunInBackground runs command/exec tasks in a goroutine. @group Execution

Example: allow command jobs to run async

scheduler.New().RunInBackground().Command("noop")

func (*JobBuilder) Saturdays

func (j *JobBuilder) Saturdays() *JobBuilder

Saturdays limits the job to Saturdays. @group Filters

Example: run only on Saturdays

scheduler.New().Saturdays().DailyAt("09:00")

func (*JobBuilder) Skip

func (j *JobBuilder) Skip(fn func() bool) *JobBuilder

Skip prevents scheduling the job if the provided condition returns true. @group Filters

Example: suppress jobs based on a switch

enabled := false
scheduler.New().Skip(func() bool { return !enabled }).Daily()

func (*JobBuilder) Sundays

func (j *JobBuilder) Sundays() *JobBuilder

Sundays limits the job to Sundays. @group Filters

Example: run only on Sundays

scheduler.New().Sundays().DailyAt("09:00")

func (*JobBuilder) Thursdays

func (j *JobBuilder) Thursdays() *JobBuilder

Thursdays limits the job to Thursdays. @group Filters

Example: run only on Thursdays

scheduler.New().Thursdays().DailyAt("09:00")

func (*JobBuilder) Timezone

func (j *JobBuilder) Timezone(zone string) *JobBuilder

Timezone sets a timezone string for the job (not currently applied to gocron Scheduler). @group Configuration

Example: tag jobs with a timezone

scheduler.New().Timezone("America/New_York").Daily()

func (*JobBuilder) Tuesdays

func (j *JobBuilder) Tuesdays() *JobBuilder

Tuesdays limits the job to Tuesdays. @group Filters

Example: run only on Tuesdays

scheduler.New().Tuesdays().DailyAt("09:00")

func (*JobBuilder) TwiceDaily

func (j *JobBuilder) TwiceDaily(h1, h2 int) *JobBuilder

TwiceDaily schedules the job to run daily at two specified hours (e.g., 1 and 13). @group Calendar

Example: run two times per day

scheduler.New().TwiceDaily(1, 13)

func (*JobBuilder) TwiceDailyAt

func (j *JobBuilder) TwiceDailyAt(h1, h2, m int) *JobBuilder

TwiceDailyAt schedules the job to run daily at two specified times (e.g., 1:15 and 13:15). @group Calendar

Example: run twice daily at explicit minutes

scheduler.New().TwiceDailyAt(1, 13, 15)

func (*JobBuilder) TwiceMonthly

func (j *JobBuilder) TwiceMonthly(d1, d2 int, hm string) *JobBuilder

TwiceMonthly schedules the job to run on two specific days of the month at the given time. @group Calendar

Example: run on two days each month

scheduler.New().TwiceMonthly(1, 15, "10:00")

func (*JobBuilder) UnlessBetween

func (j *JobBuilder) UnlessBetween(start, end string) *JobBuilder

UnlessBetween prevents the job from running between the provided HH:MM times. @group Filters

Example: pause execution overnight

scheduler.New().UnlessBetween("22:00", "06:00").EveryMinute()

func (*JobBuilder) Wednesdays

func (j *JobBuilder) Wednesdays() *JobBuilder

Wednesdays limits the job to Wednesdays. @group Filters

Example: run only on Wednesdays

scheduler.New().Wednesdays().DailyAt("09:00")

func (*JobBuilder) Weekdays

func (j *JobBuilder) Weekdays() *JobBuilder

Weekdays limits the job to run only on weekdays (Mon-Fri). @group Filters

Example: weekday-only execution

scheduler.New().Weekdays().DailyAt("09:00")

func (*JobBuilder) Weekends

func (j *JobBuilder) Weekends() *JobBuilder

Weekends limits the job to run only on weekends (Sat-Sun). @group Filters

Example: weekend-only execution

scheduler.New().Weekends().DailyAt("10:00")

func (*JobBuilder) Weekly

func (j *JobBuilder) Weekly() *JobBuilder

Weekly schedules the job to run once per week on Sunday at midnight. @group Calendar

Example: weekly maintenance

scheduler.New().Weekly()

func (*JobBuilder) WeeklyOn

func (j *JobBuilder) WeeklyOn(day int, hm string) *JobBuilder

WeeklyOn schedules the job to run weekly on a specific day of the week and time. Day uses 0 = Sunday through 6 = Saturday. @group Calendar

Example: run each Monday at 08:00

scheduler.New().WeeklyOn(1, "8:00")

func (*JobBuilder) When

func (j *JobBuilder) When(fn func() bool) *JobBuilder

When only schedules the job if the provided condition returns true. @group Filters

Example: guard scheduling with a flag

flag := true
scheduler.New().When(func() bool { return flag }).Daily()

func (*JobBuilder) WithCommandRunner

func (j *JobBuilder) WithCommandRunner(r CommandRunner) *JobBuilder

WithCommandRunner overrides command execution (default: exec.CommandContext). @group Configuration

Example: swap in a custom runner

runner := scheduler.CommandRunnerFunc(func(_ context.Context, exe string, args []string) error {
	_ = exe
	_ = args
	return nil
})

builder := scheduler.New().WithCommandRunner(runner)
_ = builder

func (*JobBuilder) WithNowFunc

func (j *JobBuilder) WithNowFunc(fn func() time.Time) *JobBuilder

WithNowFunc overrides current time (default: time.Now). Useful for tests. @group Configuration

Example: freeze time for predicates

fixed := func() time.Time { return time.Unix(0, 0) }
scheduler.New().WithNowFunc(fixed)

func (*JobBuilder) WithoutOverlapping

func (j *JobBuilder) WithoutOverlapping() *JobBuilder

WithoutOverlapping ensures the job does not run concurrently. @group Concurrency

Example: prevent overlapping runs of a slow task

scheduler.New().
	WithoutOverlapping().
	EveryFiveSeconds().
	Do(func() { time.Sleep(7 * time.Second) })

func (*JobBuilder) WithoutOverlappingWithLocker

func (j *JobBuilder) WithoutOverlappingWithLocker(locker gocron.Locker) *JobBuilder

WithoutOverlappingWithLocker ensures the job does not run concurrently across distributed systems using the provided locker. @group Concurrency

Example: use a distributed locker

locker := scheduler.LockerFunc(func(ctx context.Context, key string) (gocron.Lock, error) {
	return scheduler.LockFunc(func(context.Context) error { return nil }), nil
})

scheduler.New().
	WithoutOverlappingWithLocker(locker).
	EveryMinute().
	Do(func() {})

func (*JobBuilder) Yearly

func (j *JobBuilder) Yearly() *JobBuilder

Yearly schedules the job to run on January 1st every year at midnight. @group Calendar

Example: yearly trigger

scheduler.New().Yearly()

func (*JobBuilder) YearlyOn

func (j *JobBuilder) YearlyOn(month, day int, hm string) *JobBuilder

YearlyOn schedules the job to run every year on a specific month, day, and time. @group Calendar

Example: yearly on a specific date

scheduler.New().YearlyOn(12, 25, "06:45")

type JobEvent added in v1.3.0

type JobEvent struct {
	Type       JobEventType
	JobID      uuid.UUID
	Name       string
	TargetKind string
	Attempt    int
	Duration   time.Duration
	Error      error
	Reason     string
	OccurredAt time.Time
}

type JobEventType added in v1.3.0

type JobEventType string
const (
	JobStarted   JobEventType = "job_started"
	JobSucceeded JobEventType = "job_succeeded"
	JobFailed    JobEventType = "job_failed"
	JobSkipped   JobEventType = "job_skipped"
)

type JobMetadata

type JobMetadata struct {
	ID           uuid.UUID
	Name         string
	Schedule     string
	ScheduleType string
	TargetKind   string
	Handler      string
	Command      string
	Tags         []string
	Paused       bool
}

JobMetadata captures stored job details keyed by job ID.

type JobObserver added in v1.3.0

type JobObserver interface {
	OnJobEvent(event JobEvent)
}

type JobObserverFunc added in v1.3.0

type JobObserverFunc func(event JobEvent)

func (JobObserverFunc) OnJobEvent added in v1.3.0

func (f JobObserverFunc) OnJobEvent(event JobEvent)

type JobSkipReason added in v1.3.0

type JobSkipReason string
const (
	JobSkipPaused JobSkipReason = "paused"
)

type LockFunc

type LockFunc func(ctx context.Context) error

LockFunc adapts a function to satisfy gocron.Lock. @group Adapters

Example: unlock via a function

lock := scheduler.LockFunc(func(context.Context) error { return nil })
_ = lock.Unlock(context.Background())

func (LockFunc) Unlock

func (f LockFunc) Unlock(ctx context.Context) error

Unlock invokes the underlying function. @group Adapters

Example: invoke unlock on an adapted lock

lock := scheduler.LockFunc(func(context.Context) error { return nil })
_ = lock.Unlock(context.Background())

type LockerFunc

type LockerFunc func(ctx context.Context, key string) (gocron.Lock, error)

LockerFunc adapts a function to satisfy gocron.Locker. @group Adapters

Example: build a locker from a function

locker := scheduler.LockerFunc(func(ctx context.Context, key string) (gocron.Lock, error) {
	return scheduler.LockFunc(func(context.Context) error { return nil }), nil
})
_, _ = locker.Lock(context.Background(), "job")

func (LockerFunc) Lock

func (f LockerFunc) Lock(ctx context.Context, key string) (gocron.Lock, error)

Lock invokes the underlying function. @group Adapters

type RedisLocker

type RedisLocker struct {
	// contains filtered or unexported fields
}

RedisLocker is a simple gocron Locker backed by redis NX locks. It uses a single key per job and auto-expires after ttl.

func NewRedisLocker

func NewRedisLocker(client redisLockerClient, ttl time.Duration) *RedisLocker

NewRedisLocker creates a RedisLocker with a client and TTL. The ttl is a lease duration: when it expires, another worker may acquire the same lock key. For long-running jobs, choose ttl >= worst-case runtime plus a safety buffer. If your runtime can exceed ttl, prefer a renewing/heartbeat lock strategy. @group Locking

Example: create a redis-backed locker

client := redis.NewClient(&redis.Options{}) // replace with your client
locker := scheduler.NewRedisLocker(client, 10*time.Minute)
_, _ = locker.Lock(context.Background(), "job")

func (*RedisLocker) Lock

func (l *RedisLocker) Lock(ctx context.Context, key string) (gocron.Lock, error)

Lock obtains a lock for the job name. @group Locking

Example: acquire a lock

client := redis.NewClient(&redis.Options{})
locker := scheduler.NewRedisLocker(client, 10*time.Minute)
lock, _ := locker.Lock(context.Background(), "job")
_ = lock.Unlock(context.Background())

type Scheduler added in v1.2.0

type Scheduler struct {
	*JobBuilder
	// contains filtered or unexported fields
}

Scheduler is a high-level facade that owns a gocron scheduler instance. It starts automatically and exposes low-ceremony entrypoints for jobs.

func New added in v1.2.0

func New(options ...gocron.SchedulerOption) *Scheduler

New creates and starts a scheduler facade. It panics only if gocron scheduler construction fails. @group Construction

Example: create scheduler and run a simple interval job

s := scheduler.New()
defer s.Stop()
s.Every(15).Seconds().Do(func() {})

func NewWithError added in v1.2.0

func NewWithError(options ...gocron.SchedulerOption) (*Scheduler, error)

NewWithError creates and starts a scheduler facade and returns setup errors. @group Construction

Example: construct with explicit error handling

s, err := scheduler.NewWithError()
if err != nil {
	panic(err)
}
defer s.Stop()

func (*Scheduler) Cron added in v1.2.0

func (s *Scheduler) Cron(expr string) *JobBuilder

Cron schedules a cron-based job builder.

func (*Scheduler) Every added in v1.2.0

func (s *Scheduler) Every(interval int) *FluentEvery

Every starts an interval chain identical to JobBuilder.Every. @group Intervals

func (*Scheduler) EveryDuration added in v1.2.0

func (s *Scheduler) EveryDuration(interval time.Duration) *JobBuilder

EveryDuration schedules a duration-based interval job builder. @group Intervals

func (*Scheduler) GocronScheduler added in v1.2.0

func (s *Scheduler) GocronScheduler() gocron.Scheduler

GocronScheduler returns the underlying gocron scheduler for advanced integration. Prefer the fluent scheduler API for typical use-cases. @group Interop

func (*Scheduler) Jobs added in v1.2.0

func (s *Scheduler) Jobs() []gocron.Job

Jobs returns scheduled jobs from the underlying scheduler. @group Diagnostics

func (*Scheduler) Raw added in v1.2.0

func (s *Scheduler) Raw() gocron.Scheduler

func (*Scheduler) Shutdown added in v1.2.0

func (s *Scheduler) Shutdown() error

Shutdown gracefully shuts down the underlying scheduler. @group Lifecycle

Example: shutdown via underlying method name

s := scheduler.New()
_ = s.Shutdown()

func (*Scheduler) Start added in v1.2.0

func (s *Scheduler) Start()

Start starts the underlying scheduler. @group Lifecycle

Example: manually start (auto-started by New/NewWithError)

s := scheduler.New()
s.Start()

func (*Scheduler) Stop added in v1.2.0

func (s *Scheduler) Stop() error

Stop gracefully shuts down the scheduler. @group Lifecycle

Example: stop the scheduler

s := scheduler.New()
_ = s.Stop()

type SchedulerAdapter

type SchedulerAdapter interface {
	NewJob(job gocron.JobDefinition, task gocron.Task, options ...gocron.JobOption) (gocron.Job, error)
	Start()
	Shutdown() error
	Jobs() []gocron.Job
}

SchedulerAdapter wraps gocron.Scheduler with a small interface surface.

Directories

Path Synopsis
examples
after command
before command
between command
command command
cron command
cronexpr command
daily command
dailyat command
days command
daysofmonth command
do command
environments command
error command
every command
everyfourhours command
everyminute command
everyoddhour command
everysecond command
everysixhours command
everytenminutes command
everytenseconds command
everythreehours command
everytwohours command
everytwominutes command
everytwoseconds command
exec command
fridays command
hourly command
hourlyat command
hours command
job command
jobmetadata command
jobsinfo command
lastdayofmonth command
lock command
minutes command
mondays command
monthly command
monthlyon command
name command
new command
newcachelocker command
newredislocker command
newwitherror command
observe command
onfailure command
onsuccess command
pauseall command
pausejob command
printjobslist command
quarterly command
quarterlyon command
resumeall command
resumejob command
retainstate command
run command
runinbackground command
saturdays command
seconds command
shutdown command
skip command
start command
stop command
sundays command
thursdays command
timezone command
tuesdays command
twicedaily command
twicedailyat command
twicemonthly command
unlessbetween command
wednesdays command
weekdays command
weekends command
weekly command
weeklyon command
when command
withnowfunc command
yearly command
yearlyon command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL