Scheduler Library for Go

Schedule Go functions and commands with a fluent API built on gocron.
Quick Start · Features · Examples · API
Quick Start
Requires Go 1.25 or newer.
go get github.com/goforj/scheduler/v2Run a job every second and press Ctrl+C to stop the scheduler.
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.
// 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.
// 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.
schedule.PrintJobsList()The runnable heartbeat example shows one row. The next run time depends on when you start it.
+------------------------------------------------------------------------------------------+
| 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
Schedulerconfigures one job. Keep the returned builder for its registration result. Set a timezone or a job-level runner on that chain. CallingWithCommandRunnerorWithNowFuncdirectly on the scheduler sets the default for new job builders. When,Skip, andEnvironmentsdecide whether to register a job. Day and time-window filters run before each task. UseRunIffor 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. RestartSchedulequeues 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
Adapters
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. Use Exec for arbitrary executables. The job context and a ten-minute timeout bound the run.
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.
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.
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.
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.
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.
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.
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.
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(context.Context) error { return nil })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(context.Context) error { return nil })
fmt.Println(b.Job() != nil)
// Output: trueJobs
Jobs returns scheduled jobs from the underlying scheduler.
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.
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.
scheduler.New().RunInBackground().DailyAt("03:00").Command("reports:generate")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 from Sunday through Saturday.
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")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.
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.
scheduler.New().Saturdays().DailyAt("09:00")Skip
Skip suppresses registration if the condition returns true at registration.
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 task execution to Monday through Friday. The job registers on any day.
scheduler.New().Weekdays().DailyAt("09:00")Weekends
Weekends limits task execution to Saturday and Sunday. The job registers on any day.
scheduler.New().Weekends().DailyAt("10:00")When
When registers the job only if the condition returns true at registration.
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(context.Context) {}).Daily()Before
Before sets a hook to run before task execution.
scheduler.New().Before(func(context.Context) {}).Daily()OnFailure
OnFailure sets a hook to run after failed task execution.
scheduler.New().OnFailure(func(context.Context, error) {}).Daily()OnSuccess
OnSuccess sets a hook to run after successful task execution.
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.
schedule := scheduler.New()
defer schedule.Stop()
native := schedule.GocronScheduler()
fmt.Println(native.JobsWaitingInQueue())
// Output: 0Intervals
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.
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.
scheduler.New().EveryFifteenMinutes().Do(func(context.Context) error { return nil })EveryFifteenSeconds
EveryFifteenSeconds schedules the job to run every 15 seconds.
scheduler.New().EveryFifteenSeconds().Do(func(context.Context) error { return nil })EveryFiveMinutes
EveryFiveMinutes schedules the job to run every 5 minutes.
scheduler.New().EveryFiveMinutes().Do(func(context.Context) error { return nil })EveryFiveSeconds
EveryFiveSeconds schedules the job to run every 5 seconds.
scheduler.New().EveryFiveSeconds().Do(func(context.Context) error { return nil })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(context.Context) error { return nil })EveryMinute
EveryMinute schedules the job to run every 1 minute.
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.
scheduler.New().EveryOddHour(10)EverySecond
EverySecond schedules the job to run every 1 second.
scheduler.New().EverySecond().Do(func(context.Context) error { return nil })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(context.Context) error { return nil })EveryTenSeconds
EveryTenSeconds schedules the job to run every 10 seconds.
scheduler.New().EveryTenSeconds().Do(func(context.Context) error { return nil })EveryThirtyMinutes
EveryThirtyMinutes schedules the job to run every 30 minutes.
scheduler.New().EveryThirtyMinutes().Do(func(context.Context) error { return nil })EveryThirtySeconds
EveryThirtySeconds schedules the job to run every 30 seconds.
scheduler.New().EveryThirtySeconds().Do(func(context.Context) error { return nil })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(context.Context) error { return nil })EveryTwentySeconds
EveryTwentySeconds schedules the job to run every 20 seconds.
scheduler.New().EveryTwentySeconds().Do(func(context.Context) error { return nil })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(context.Context) error { return nil })EveryTwoSeconds
EveryTwoSeconds schedules the job to run every 2 seconds.
scheduler.New().EveryTwoSeconds().Do(func(context.Context) error { return nil })Hourly
Hourly schedules the job to run every hour.
scheduler.New().Hourly().Do(func(context.Context) error { return nil })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(context.Context) error { return nil })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
Lock
Lock obtains a lock for the job name.
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
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 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.
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.
schedule := scheduler.New()
defer schedule.Stop()
admin := schedule.Admin()
fmt.Println(admin.IsPausedAll())
// Output: falseJobMetadata
JobMetadata returns a detached copy of tracked metadata for registered jobs.
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.
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.
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.
scheduler.New().Name("cache:refresh").HourlyAt(15)PauseSchedule
PauseSchedule pauses a fluent schedule by ID. Native jobs return errors.ErrUnsupported.
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.
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.
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.
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.
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.
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: trueIsPausedAll
IsPausedAll reports whether global pause is enabled.
schedule := scheduler.New()
defer schedule.Stop()
if err := schedule.PauseAll(); err != nil {
fmt.Println(err)
return
}
fmt.Println(schedule.IsPausedAll())
// Output: trueNewCachePauseStore
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.
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.
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.
s := scheduler.New()
_ = s.PauseAll()PauseJob
PauseJob pauses execution for a specific fluent job. RunNow calls for that job are skipped while paused.
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.
s := scheduler.New()
_ = s.ResumeAll()ResumeJob
ResumeJob resumes a paused job by ID.
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.
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.
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.
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(context.Context) error { return nil })Development
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 changeUse 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.