Skip to content

Scheduler Library for Go ​

scheduler logo

Schedule Go functions and commands with a fluent API built on gocron.

Go ReferenceLicense: MITGo TestGo versionLatest tagPublished GitHub release countTests

Quick Start · Features · Examples · API

Quick Start ​

Requires Go 1.25 or newer.

sh
go get github.com/goforj/scheduler/v2

Run a job every second and press Ctrl+C to stop the scheduler.

go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"

	"github.com/goforj/scheduler/v2"
)

// main prints a heartbeat until interrupted.
func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	schedule := scheduler.New()
	job := schedule.EverySecond().Do(func(context.Context) error {
		fmt.Println("heartbeat")
		// Output: heartbeat
		return nil
	})
	if err := job.Error(); err != nil {
		log.Fatal(err)
	}

	// Keep the scheduler running until Ctrl+C.
	<-ctx.Done()
	if err := schedule.Stop(); err != nil {
		log.Fatal(err)
	}
}

Scheduling options ​

Schedule your app's generateReports(ctx) function using the scheduler above.

go
// Run at 10:30 a.m. New York time on weekdays and prevent overlapping reports.
report := schedule.Cron("30 10 * * 1-5").
	Name("reports:generate").
	Timezone("America/New_York").
	WithoutOverlapping().
	Do(generateReports)
if err := report.Error(); err != nil {
	log.Fatal(err)
}

You can also schedule a subcommand of your CLI.

go
// Run this binary's billing:reconcile command daily at 3 a.m. local time.
reconcile := schedule.DailyAt("03:00").Command("billing:reconcile", "--retry=3")
if err := reconcile.Error(); err != nil {
	log.Fatal(err)
}

List jobs as an ASCII table ​

Call PrintJobsList after registration to check which jobs are scheduled and when they will run.

go
schedule.PrintJobsList()

The runnable heartbeat example shows one row. The next run time depends on when you start it.

text
+------------------------------------------------------------------------------------------+
| Scheduler Jobs › (1)
+-----------+----------+----------+-----------------------+--------------------+-----------+
| Name      | Type     | Schedule | Handler               | Next Run           | Tags      |
+-----------+----------+----------+-----------------------+--------------------+-----------+
| heartbeat | function | every 1s | main.main (anon func) | in 1s Dec 2 2:24AM | env=local |
+-----------+----------+----------+-----------------------+--------------------+-----------+

Features ​

  • Schedule Go functions, CLI subcommands, or external programs with intervals, cron, and calendar helpers.
  • Prevent overlapping runs and use a shared lock across scheduler instances.
  • Limit when jobs run, and use lifecycle hooks to handle success or failure.
  • Inspect next runs and pause or resume individual jobs.

Distributed locking ​

Use NewCacheLocker with a GoForj Cache driver that supports owner-aware leases. Configure each scheduler instance to use the same shared backend and cache prefix, give the job the same explicit name, and choose a lease TTL longer than the expected job runtime. The in-memory driver coordinates jobs within one process when they share a store. On first use, shared stores are checked with a disposable ownership probe. Give each job an explicit name when using gocron's scheduler-wide locker, so unrelated fluent jobs use distinct lock keys.

For an existing shared lock namespace, see Upgrading.

The lease is released when the job finishes. A replica that triggers the same occurrence later can start it after that release. Use OncePerOccurrence to keep a dispatch claim beyond task completion. Give each job a unique name in the shared cache namespace. Every replica uses that name and the same logical occurrence ID. Retain claims past the latest expected duplicate and use a store configured to keep them. The caller supplies the ID, such as the date of the report being generated. Derive the ID from the work itself if execution can slip into a different reporting period. A failed or interrupted task keeps its claim until expiry. A manual admin run can retry it explicitly.

If you already manage a Redis client, NewRedisLocker can use it directly. You can also supply your own gocron.Locker.

Execution behavior ​

  • A new fluent chain on Scheduler configures one job. Keep the returned builder for its registration result. Set a timezone or a job-level runner on that chain. Calling WithCommandRunner or WithNowFunc directly on the scheduler sets the default for new job builders.
  • When, Skip, and Environments decide whether to register a job. Day and time-window filters run before each task. Use RunIf for a live condition that is checked on every run. A listed next run is the next trigger and may be filtered.
  • Jobs keep scheduler cancellation and deadlines when a decorator supplies a context. Derive from the supplied context to carry its values forward. If shutdown cancels a before hook's context, the attempt ends with a cancellation error before the task starts. The scheduler tracks tasks through completion, including calls that still use RunInBackground.
  • RestartSchedule queues one manual invocation without clearing any pause or changing the recurring schedule. It applies native execution limits and locks. Watch job events for the result. Removing or replacing the recurring job cancels a manual run that is still queued.

To pause recurring work across replicas, configure WithPauseStore. Each replica reads the same flag before running a task. NewCachePauseStore retains it until the configured TTL or an explicit resume. Use a persistent implementation of PauseStore for a pause that must survive cache eviction and last until resumed. A backend read error suppresses recurring runs and appears in the skip event and native gocron error listeners. The Cache null driver is rejected for pause flags and occurrence claims.

Runnable examples ​

The examples directory contains programs generated from GoDoc. The test suite checks that they build.

API Index ​

GroupFunctions
AdaptersRun · Unlock
CalendarDaily · DailyAt · DaysOfMonth · LastDayOfMonth · Monthly · MonthlyOn · Quarterly · QuarterlyOn · TwiceDaily · TwiceDailyAt · TwiceMonthly · Weekly · WeeklyOn · Yearly · YearlyOn
CommandsCommand · Exec
ConcurrencyOncePerOccurrence · WithoutOverlapping · WithoutOverlappingWithLocker
ConfigurationTimezone · WithCommandRunner · WithNowFunc
ConstructionNew · NewWithError
DiagnosticsCronExpr · Error · Job · Jobs · PrintJobsList
ExecutionRunInBackground
FiltersBetween · Days · Environments · Fridays · Mondays · RunIf · Saturdays · Skip · Sundays · Thursdays · Tuesdays · UnlessBetween · Wednesdays · Weekdays · Weekends · When
HooksAfter · Before · OnFailure · OnSuccess
InteropGocronScheduler
IntervalsEvery · 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
LifecycleShutdown · Start · Stop
LockingLock · NewCacheLocker · NewRedisLocker
MetadataAdmin · JobMetadata · JobsInfo · ListSchedules · Name · PauseSchedule · RestartSchedule · ResumeSchedule
OtherNewJobBuilder · WithTaskContextDecorator
Runtime controlIsJobPaused · IsPausedAll · NewCachePauseStore · Observe · PauseAll · PauseJob · ResumeAll · ResumeJob · WithPauseStore
State managementRetainState
TriggersCron · Do

Adapters ​

Run ​

Run executes the underlying function.

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

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

go
scheduler.New().Daily()

DailyAt ​

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

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

DaysOfMonth ​

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

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

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

Monthly ​

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

go
scheduler.New().Monthly()

MonthlyOn ​

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

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

Quarterly ​

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

go
scheduler.New().Quarterly()

QuarterlyOn ​

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

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

TwiceDaily ​

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

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

TwiceDailyAt ​

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

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

TwiceMonthly ​

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

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

Weekly ​

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

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

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

Yearly ​

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

go
scheduler.New().Yearly()

YearlyOn ​

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

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

Commands ​

Command ​

Command executes the current binary with the given subcommand and variadic args. Use Exec for arbitrary executables. The job context and a ten-minute timeout bound the run.

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

Exec ​

Exec runs an external executable with variadic args. The job context and a ten-minute timeout bound the run.

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

Concurrency ​

OncePerOccurrence ​

OncePerOccurrence keeps one claim for a named job and caller-supplied occurrence ID. All replicas must return the same ID for the same logical occurrence and share the store. Retain claims longer than the maximum duplicate arrival window. Manual admin runs bypass claims.

go
schedule := scheduler.New()
defer schedule.Stop()
store := cache.NewMemoryStore(context.Background())
job := schedule.DailyAt("09:00").Timezone("UTC").Name("reports:daily").
	OncePerOccurrence(store, 48*time.Hour, func(context.Context) (string, error) {
		// Use the reporting date in UTC as the occurrence ID.
		return time.Now().UTC().Format(time.DateOnly), nil
	}).Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
}

WithoutOverlapping ​

WithoutOverlapping ensures the job does not run concurrently.

go
scheduler.New().
	WithoutOverlapping().
	EveryFiveSeconds().
	Do(func(context.Context) error { time.Sleep(7 * time.Second); return nil })

WithoutOverlappingWithLocker ​

WithoutOverlappingWithLocker prevents concurrent runs while the shared lease is held. Give the job the same explicit name on each scheduler instance. An unnamed function job defaults to its handler identity unless a native name is configured. A nil locker fails registration. Use WithoutOverlapping for in-process protection.

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

scheduler.New().
	Name("reports:generate").
	WithoutOverlappingWithLocker(locker).
	EveryMinute().
	Do(func(context.Context) error { return nil })

Configuration ​

Timezone ​

Timezone sets the zone used by this job’s cron expression and calendar filters. An invalid zone produces a registration error.

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

WithCommandRunner ​

WithCommandRunner sets the default runner when called on Scheduler. Call it on a job builder to override the runner for that registration.

go
schedule := scheduler.New()
defer schedule.Stop()
schedule.WithCommandRunner(scheduler.CommandRunnerFunc(func(_ context.Context, exe string, args []string) error {
	fmt.Println(exe, args)
	return nil
}))

WithNowFunc ​

WithNowFunc sets the default calendar clock when called on Scheduler. Call it on a job builder to override the calendar clock for that registration.

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

go
s := scheduler.New()
defer s.Stop()
s.Every(15).Seconds().Do(func(context.Context) error { return nil })

NewWithError ​

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

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

Diagnostics ​

CronExpr ​

CronExpr returns the cron expression string configured for this job.

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

Error ​

Error returns the error if any occurred during job scheduling.

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

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

Jobs ​

Jobs returns scheduled jobs from the underlying scheduler.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryMinute().Name("reports:generate").Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
for _, entry := range schedule.Jobs() {
	fmt.Println(entry.Name())
	// Output: reports:generate
}

PrintJobsList ​

PrintJobsList renders and prints the scheduler job table to stdout.

go
s := scheduler.New()
defer s.Stop()
s.EverySecond().Name("heartbeat").Do(func(context.Context) error { return nil })
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 is retained for source compatibility. The scheduler already runs tasks asynchronously and tracks them through completion for shutdown and locks.

go
scheduler.New().RunInBackground().DailyAt("03:00").Command("reports:generate")

Filters ​

Between ​

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

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

Days ​

Days limits the job to a specific set of weekdays from Sunday through Saturday.

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

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

Fridays ​

Fridays limits the job to Fridays.

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

Mondays ​

Mondays limits the job to Mondays.

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

RunIf ​

RunIf evaluates a condition before each invocation, including manual runs. Every condition must succeed. Return an error to skip the run and report the failure. Conditions must be safe for concurrent use if the job allows overlapping runs.

go
schedule := scheduler.New()
defer schedule.Stop()
schedule.EveryMinute().RunIf(func(ctx context.Context) (bool, error) {
	_, err := os.Stat("reports.csv")
	if os.IsNotExist(err) {
		return false, nil
	}
	return err == nil, err
}).Do(func(context.Context) error { return nil })

Saturdays ​

Saturdays limits the job to Saturdays.

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

Skip ​

Skip suppresses registration if the condition returns true at registration.

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

Sundays ​

Sundays limits the job to Sundays.

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

Thursdays ​

Thursdays limits the job to Thursdays.

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

Tuesdays ​

Tuesdays limits the job to Tuesdays.

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

UnlessBetween ​

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

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

Wednesdays ​

Wednesdays limits the job to Wednesdays.

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

Weekdays ​

Weekdays limits task execution to Monday through Friday. The job registers on any day.

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

Weekends ​

Weekends limits task execution to Saturday and Sunday. The job registers on any day.

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

When ​

When registers the job only if the condition returns true at registration.

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

Hooks ​

After ​

After sets a hook to run after task execution.

go
scheduler.New().After(func(context.Context) {}).Daily()

Before ​

Before sets a hook to run before task execution.

go
scheduler.New().Before(func(context.Context) {}).Daily()

OnFailure ​

OnFailure sets a hook to run after failed task execution.

go
scheduler.New().OnFailure(func(context.Context, error) {}).Daily()

OnSuccess ​

OnSuccess sets a hook to run after successful task execution.

go
scheduler.New().OnSuccess(func(context.Context) {}).Daily()

Interop ​

GocronScheduler ​

GocronScheduler exposes the native scheduler API for advanced integration. A job replaced through Update becomes a native job and loses its fluent execution policy.

go
schedule := scheduler.New()
defer schedule.Stop()
native := schedule.GocronScheduler()
fmt.Println(native.JobsWaitingInQueue())
// Output: 0

Intervals ​

Every ​

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

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

EveryDuration ​

EveryDuration schedules a duration-based interval job builder.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryDuration(90 * time.Second).Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
}

EveryFifteenMinutes ​

EveryFifteenMinutes schedules the job to run every 15 minutes.

go
scheduler.New().EveryFifteenMinutes().Do(func(context.Context) error { return nil })

EveryFifteenSeconds ​

EveryFifteenSeconds schedules the job to run every 15 seconds.

go
scheduler.New().EveryFifteenSeconds().Do(func(context.Context) error { return nil })

EveryFiveMinutes ​

EveryFiveMinutes schedules the job to run every 5 minutes.

go
scheduler.New().EveryFiveMinutes().Do(func(context.Context) error { return nil })

EveryFiveSeconds ​

EveryFiveSeconds schedules the job to run every 5 seconds.

go
scheduler.New().EveryFiveSeconds().Do(func(context.Context) error { return nil })

EveryFourHours ​

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

go
scheduler.New().EveryFourHours(25)

EveryFourMinutes ​

EveryFourMinutes schedules the job to run every 4 minutes.

go
scheduler.New().EveryFourMinutes().Do(func(context.Context) error { return nil })

EveryMinute ​

EveryMinute schedules the job to run every 1 minute.

go
scheduler.New().EveryMinute().Do(func(context.Context) error { return nil })

EveryOddHour ​

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

go
scheduler.New().EveryOddHour(10)

EverySecond ​

EverySecond schedules the job to run every 1 second.

go
scheduler.New().EverySecond().Do(func(context.Context) error { return nil })

EverySixHours ​

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

go
scheduler.New().EverySixHours(30)

EveryTenMinutes ​

EveryTenMinutes schedules the job to run every 10 minutes.

go
scheduler.New().EveryTenMinutes().Do(func(context.Context) error { return nil })

EveryTenSeconds ​

EveryTenSeconds schedules the job to run every 10 seconds.

go
scheduler.New().EveryTenSeconds().Do(func(context.Context) error { return nil })

EveryThirtyMinutes ​

EveryThirtyMinutes schedules the job to run every 30 minutes.

go
scheduler.New().EveryThirtyMinutes().Do(func(context.Context) error { return nil })

EveryThirtySeconds ​

EveryThirtySeconds schedules the job to run every 30 seconds.

go
scheduler.New().EveryThirtySeconds().Do(func(context.Context) error { return nil })

EveryThreeHours ​

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

go
scheduler.New().EveryThreeHours(20)

EveryThreeMinutes ​

EveryThreeMinutes schedules the job to run every 3 minutes.

go
scheduler.New().EveryThreeMinutes().Do(func(context.Context) error { return nil })

EveryTwentySeconds ​

EveryTwentySeconds schedules the job to run every 20 seconds.

go
scheduler.New().EveryTwentySeconds().Do(func(context.Context) error { return nil })

EveryTwoHours ​

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

go
scheduler.New().EveryTwoHours(15)

EveryTwoMinutes ​

EveryTwoMinutes schedules the job to run every 2 minutes.

go
scheduler.New().EveryTwoMinutes().Do(func(context.Context) error { return nil })

EveryTwoSeconds ​

EveryTwoSeconds schedules the job to run every 2 seconds.

go
scheduler.New().EveryTwoSeconds().Do(func(context.Context) error { return nil })

Hourly ​

Hourly schedules the job to run every hour.

go
scheduler.New().Hourly().Do(func(context.Context) error { return nil })

HourlyAt ​

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

go
scheduler.New().HourlyAt(5)

Hours ​

Hours schedules the job to run every X hours.

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

Minutes ​

Minutes schedules the job to run every X minutes.

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

Seconds ​

Seconds schedules the job to run every X seconds.

go
scheduler.New().Every(3).Seconds().Do(func(context.Context) error { return nil })

Lifecycle ​

Shutdown ​

Shutdown gracefully shuts down the underlying scheduler.

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

Start ​

Start starts the underlying scheduler.

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

Stop ​

Stop gracefully shuts down the scheduler.

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

Locking ​

Lock ​

Lock obtains a lock for the job name.

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

NewCacheLocker ​

NewCacheLocker creates a CacheLocker with a cache lock client and TTL. The client must expose an owner-aware store or implement its acquisition and release operations directly. In-memory stores coordinate within one process. On first use, shared stores are checked with a disposable lease. 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

go
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

go
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 client must support Eval for atomic release of the owner token. 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.

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

Metadata ​

Admin ​

Admin returns a facade for scheduler inspection and control operations.

go
schedule := scheduler.New()
defer schedule.Stop()
admin := schedule.Admin()
fmt.Println(admin.IsPausedAll())
// Output: false

JobMetadata ​

JobMetadata returns a detached copy of tracked metadata for registered jobs.

go
b := scheduler.New().EverySecond().Do(func(context.Context) error { return nil })
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.

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

ListSchedules ​

ListSchedules returns a stable UI-friendly snapshot of the configured schedules.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryMinute().Name("reports:generate").Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
for _, info := range schedule.Admin().ListSchedules() {
	fmt.Println(info.Name)
	// Output: reports:generate
}

Name ​

Name sets the job name used in diagnostics and as the distributed lock key. Command and Exec default to the command or executable name.

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

PauseSchedule ​

PauseSchedule pauses a fluent schedule by ID. Native jobs return errors.ErrUnsupported.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryMinute().Name("reports:generate").Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
if err := schedule.Admin().PauseSchedule(job.Job().ID().String()); err != nil {
	fmt.Println(err)
}

RestartSchedule ​

RestartSchedule queues one immediate run of the selected job. For Scheduler jobs, this run bypasses pauses and calendar filters without changing them. Global execution limits and job locks still apply. The request expires if the scheduler cannot admit it within one minute. Job events report job-level lock rejection, cancellation, and admission timeout. For scheduler-wide lock rejection, use gocron's AfterLockError listener.

go
schedule := scheduler.New()
defer schedule.Stop()
done := make(chan struct{})
job := schedule.EveryDuration(time.Hour).Name("reports:generate").Do(func(context.Context) error {
	fmt.Println("report generated")
	// Output: report generated
	close(done)
	return nil
})
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
if err := schedule.Admin().RestartSchedule(job.Job().ID().String()); err != nil {
	fmt.Println(err)
	return
}
select {
case <-done:
case <-time.After(time.Second):
	fmt.Println("manual run timed out")
}

ResumeSchedule ​

ResumeSchedule resumes a fluent schedule by ID. Native jobs return errors.ErrUnsupported.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryMinute().Name("reports:generate").Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
admin := schedule.Admin()
id := job.Job().ID().String()
if err := admin.PauseSchedule(id); err != nil {
	fmt.Println(err)
	return
}
if err := admin.ResumeSchedule(id); err != nil {
	fmt.Println(err)
}

Other ​

NewJobBuilder ​

NewJobBuilder creates a builder for a caller-owned scheduler adapter.

go
native, err := gocron.NewScheduler()
if err != nil {
	fmt.Println(err)
	return
}
defer native.Shutdown()

job := scheduler.NewJobBuilder(native).EveryMinute().Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
native.Start()

WithTaskContextDecorator ​

WithTaskContextDecorator sets the decorator for subsequent task invocations. The task keeps native cancellation and deadlines. Derive from the supplied context to carry existing values forward. Returning nil preserves it as is.

go
schedule := scheduler.New()
defer schedule.Stop()
type contextKey string
const serviceKey contextKey = "service"
schedule.WithTaskContextDecorator(func(ctx context.Context) context.Context {
	return context.WithValue(ctx, serviceKey, "reporting")
})

Runtime control ​

IsJobPaused ​

IsJobPaused reports whether a specific job is paused.

go
schedule := scheduler.New()
defer schedule.Stop()
job := schedule.EveryMinute().Name("reports:generate").Do(func(context.Context) error { return nil })
if err := job.Error(); err != nil {
	fmt.Println(err)
	return
}
id := job.Job().ID()
if err := schedule.PauseJob(id); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(schedule.IsJobPaused(id))
// Output: true

IsPausedAll ​

IsPausedAll reports whether global pause is enabled.

go
schedule := scheduler.New()
defer schedule.Stop()
if err := schedule.PauseAll(); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(schedule.IsPausedAll())
// Output: true

NewCachePauseStore ​

NewCachePauseStore creates a shared pause flag that expires after ttl. Use the same storage-capable cache backend, prefix, and key on every scheduler replica. Use a persistent PauseStore implementation for a pause that must remain until resumed.

go
store := cache.NewMemoryStore(context.Background())
pause, err := scheduler.NewCachePauseStore(store, "reporting", 30*time.Minute)
if err != nil {
	fmt.Println(err)
	return
}
if err := pause.SetPaused(context.Background(), true); err != nil {
	fmt.Println(err)
}

Observe ​

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

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

PauseAll ​

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

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

PauseJob ​

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

go
s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func(context.Context) error { return nil })
_ = s.PauseJob(b.Job().ID())

ResumeAll ​

ResumeAll resumes execution for all paused jobs.

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

ResumeJob ​

ResumeJob resumes a paused job by ID.

go
s := scheduler.New()
b := s.EverySecond().Name("heartbeat").Do(func(context.Context) error { return nil })
_ = s.ResumeJob(b.Job().ID())

WithPauseStore ​

WithPauseStore shares PauseAll and ResumeAll across replicas using store. Configure it before registering jobs. A nil store selects the in-process flag. If a shared flag cannot be read, recurring runs are skipped until it is readable.

go
store := cache.NewMemoryStore(context.Background())
pause, err := scheduler.NewCachePauseStore(store, "reporting", time.Hour)
if err != nil {
	fmt.Println(err)
	return
}
schedule := scheduler.New().WithPauseStore(pause)
defer schedule.Stop()
if err := schedule.PauseAll(); err != nil {
	fmt.Println(err)
}

State management ​

RetainState ​

RetainState allows the job to retain its state after execution.

go
builder := scheduler.New().EverySecond().RetainState()
builder.Do(func(context.Context) error { return nil })
builder.Do(func(context.Context) error { return nil })

Triggers ​

Cron ​

Cron sets the cron expression for the job. A leading TZ or CRON_TZ directive takes precedence over Timezone.

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

Do ​

Do schedules the job with the provided task function.

go
scheduler.New().Name("cleanup").Cron("0 0 * * *").Do(func(context.Context) error { return nil })

Development ​

sh
make test        # Run tests and build the examples
make test-race   # Run the suite with the race detector
make vet         # Run static checks
make generate    # Regenerate the README API reference and runnable examples
make docs-watch  # Regenerate docs when Go sources change

Use make help for all targets. Edit GoDoc to change generated examples.

Upgrading ​

Keep fluent configuration on the returned builder. To reuse a builder deliberately, use RetainState. Calendar filters now apply to each invocation, including schedules registered outside the permitted window.

Cache lock adapters require an owner-aware backend or an in-process memory store. Redis clients and their credentials must support EVAL. For another backend, supply an owner-aware gocron.Locker. When upgrading from v2.2.0 or earlier, drain older workers that share the lock namespace. An old worker can delete a successor's lease after its own expires. An explicit Name on a Command or Exec job now selects its lock key. Unnamed function jobs with a job-level locker use the handler identity when there is no native name. Set an explicit name to keep keys stable across builds or to distinguish separate schedules of the same handler.

Manual runs register a one-time native job and inherit global job options. If you set a fixed global start date, use gocron.WithStartDateTimePast so manual runs can be registered after that date passes.

Using with GoForj ​

GoForj Apps register schedules in the scheduler runtime and inject the jobs they run. Keep recurring business work in jobs instead of the schedule registry.

For the App workflow, see Scheduler.