Documentation
¶
Overview ¶
Package schedule runs functions on a calendar and defers one-off typed tasks. The Scheduler owns what runs; a Driver owns when it runs.
scheduler := schedule.New(driver)
err := scheduler.Add(
schedule.NewEntry("prune", prune, func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Every(5 * time.Minute))
}),
schedule.NewEntry("report", report, func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Hour(3))
entry.Timeout(time.Hour)
}),
)
if err != nil {
return err
}
var Remind = schedule.NewTask[Reminder]("remind")
if err := scheduler.Handle(Remind, remind); err != nil {
return err
}
id, err := scheduler.After(ctx, Remind, Reminder{
UserID: 42,
}, 10*time.Minute)
if err != nil {
return err
}
fmt.Println(id)
Register the scheduler during application composition:
compose.Run(scheduler.Run)
Entries are immutable snapshots. NewEntry invokes its construction callbacks directly once, in order on one fresh EntryBuilder, then checks the completed declaration. Supply EntryBuilder.When; there is no default schedule. Names, nil execution functions, invalid specs, and negative timeouts are ordinary errors reported by Entry.Err and Scheduler.Add. The first error is kept. Supplied nil construction callbacks and callback panics propagate; expanded nil or empty callback slices supply no edits. Retained drafts cannot change published entries. Spec keeps its immutable fluent API. Scheduler.Entries returns an eager collection snapshot in registration order. Filtering it does not change registrations or observe later Add calls; immutable entries retain shared execution functions and their captures.
Time zones ¶
Start every Spec with UTC, which has no daylight saving time and runs the same way everywhere. Use In only when the wall-clock time matters to people, such as a digest at 09:00 in Amsterdam.
Daylight saving time ¶
In a zone with daylight saving time, a wall-clock time that does not exist because clocks jump forward is skipped for that day. A wall-clock time that occurs twice because clocks go back runs once, at its first occurrence. Scheduler.Add logs a warning at startup when an entry in a non-UTC zone has a time inside such a transition during the next year. Prefer UTC for entries that must run every day.
Zone data comes from the operating system. On minimal images without zone files, add import _ "time/tzdata" to the program so time.LoadLocation works.
Registration ¶
Entries and task handlers are closures registered by name in every process that runs the scheduler, so each process must register the same names before Scheduler.Run. Entries and tasks share one namespace. Only the name and a JSON payload travel through the driver.
Telemetry ¶
With Builder.Telemetry, or telemetry.Default when it is not set, every run emits a root span "schedule run", labeled with the entry or task name, whose outcome is ok, skipped or failed, plus the arkoren.schedule.run.count and arkoren.schedule.run.duration metrics. Spans that cache, database and storage calls start from the entry's context become its children. Task payloads, error text and job identifiers are never recorded. Disabled telemetry costs nothing.
sched := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Telemetry(app.Telemetry())
})
Scheduler construction uses Builder callbacks, separate from EntryBuilder definitions. Callbacks run directly once in order on one fresh draft; nil entries panic and nil/empty slice expansion omits edits. Publication detaches retained roots while keeping logger, telemetry and event services shared.
Events ¶
With Builder.Events, every failed run publishes RunFailed ("schedule.run.failed") with the name, duration, and error, and every run that returns ErrSkipped publishes RunSkipped ("schedule.run.skipped") with the name and duration, for every driver. Successful runs publish nothing. Scheduler.At and Scheduler.After publish TaskDeferred ("schedule.task.deferred") with the task name, job identifier, and run time, never the payload. Scheduler.Cancel publishes TaskCanceled ("schedule.task.canceled") with the job identifier whenever it succeeds, including for an unknown or finished identifier, because the driver cannot tell those apart.
sched := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Events(app.Events())
})
Index ¶
- Variables
- type Builder
- type BuilderFunc
- type Dispatch
- type Driver
- type Entry
- type EntryBuilder
- type EntryBuilderFunc
- type Job
- type RunFailedEvent
- type RunSkippedEvent
- type Scheduler
- func (scheduler *Scheduler) Add(entries ...Entry) error
- func (scheduler *Scheduler) After[T any](ctx context.Context, task Task[T], payload T, delay time.Duration) (string, error)
- func (scheduler *Scheduler) At[T any](ctx context.Context, task Task[T], payload T, when time.Time) (string, error)
- func (scheduler *Scheduler) Cancel(ctx context.Context, id string) error
- func (scheduler *Scheduler) Driver() Driver
- func (scheduler *Scheduler) DriverAs[T any]() (T, bool)
- func (scheduler *Scheduler) Entries() collection.Slice[Entry]
- func (scheduler *Scheduler) Handle[T any](task Task[T], fn func(context.Context, T) error) error
- func (scheduler *Scheduler) MCPTools(prefix string) []mcp.Tool
- func (scheduler *Scheduler) Run(ctx context.Context) error
- func (scheduler *Scheduler) RunNow(ctx context.Context, entryName string) error
- type Spec
- func (spec Spec) Cron(expression string) Spec
- func (spec Spec) Day(values ...int) Spec
- func (spec Spec) Err() error
- func (spec Spec) Every(duration time.Duration) Spec
- func (spec Spec) Expression() string
- func (spec Spec) HasSeconds() bool
- func (spec Spec) Hour(values ...int) Spec
- func (spec Spec) Location() *time.Location
- func (spec Spec) Minute(values ...int) Spec
- func (spec Spec) Month(values ...time.Month) Spec
- func (spec Spec) Next(after time.Time) time.Time
- func (spec Spec) On(days ...time.Weekday) Spec
- func (spec Spec) Second(values ...int) Spec
- func (spec Spec) Weekdays() Spec
- func (spec Spec) Weekends() Spec
- type Task
- type TaskCanceledEvent
- type TaskDeferredEvent
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrDuplicateName = errors.New("duplicate schedule name")
ErrDuplicateName reports a second entry or task registered under one name. Registration remains unchanged when an atomic Add call finds a duplicate.
if err := scheduler.Add(entry, entry); errors.Is(err, schedule.ErrDuplicateName) {
return err
}
var ErrInvalidEntry = errors.New("invalid schedule entry")
ErrInvalidEntry reports an invalid Spec, Entry, or task registration: a bad spec or timeout, a missing spec, a nil function, or a zero time.
err := schedule.UTC().Hour(25).Err() fmt.Println(errors.Is(err, schedule.ErrInvalidEntry)) // true
var ErrInvalidName = errors.New("invalid schedule name")
ErrInvalidName reports an entry or task name that is not 1-64 lowercase letters, digits, or hyphens, or that starts or ends with a hyphen.
entry := schedule.NewEntry("Bad Name", report)
fmt.Println(errors.Is(entry.Err(), schedule.ErrInvalidName)) // true
var ErrRunning = errors.New("scheduler is running")
ErrRunning reports a registration attempted after Scheduler.Run started. It also rejects repeated facade Run calls, including after the first returns.
if err := scheduler.Add(entry); errors.Is(err, schedule.ErrRunning) {
return err
}
var ErrSkipped = errors.New("skipped")
ErrSkipped is returned by a function to report that it chose not to run, for example because another instance holds a lock. The scheduler logs the run as skipped and does not treat it as a failure.
if anotherWorkerOwnsRun {
return schedule.ErrSkipped
}
var ErrUnknownName = errors.New("unknown schedule name")
ErrUnknownName reports a name that no registered entry or task uses. An entry can also return this identity from a nested scheduling operation.
if err := scheduler.RunNow(ctx, "missing"); errors.Is(err, schedule.ErrUnknownName) {
return err
}
var ErrUnsupported = errors.New("unsupported by schedule driver")
ErrUnsupported reports an operation the driver cannot perform, such as deferred jobs on a driver without durable storage. Inspect the selected driver's documented capabilities rather than assuming that all Driver implementations support deferred or zoned execution.
_, err := scheduler.At(ctx, Remind, reminder, due)
if errors.Is(err, schedule.ErrUnsupported) {
return err
}
var RunFailed = event.NewTopic[RunFailedEvent]("schedule.run.failed")
RunFailed is published when an entry or task run returns an error other than ErrSkipped, whether the driver started it or Scheduler.RunNow did. Driver retry policy is independent of this local notification.
unsubscribe, err := bus.Listen(schedule.RunFailed, recordFailure)
if err != nil {
return err
}
compose.Defer(unsubscribe)
var RunSkipped = event.NewTopic[RunSkippedEvent]("schedule.run.skipped")
RunSkipped is published when an entry or task run returns ErrSkipped, whether the driver started it or Scheduler.RunNow did. Skips are not failures: RunFailed is not published for them.
unsubscribe, err := bus.Listen(schedule.RunSkipped, recordSkip)
if err != nil {
return err
}
compose.Defer(unsubscribe)
var TaskCanceled = event.NewTopic[TaskCanceledEvent]("schedule.task.canceled")
TaskCanceled is published when Scheduler.Cancel returns successfully. The driver contract treats an unknown or already finished identifier as success and does not report which case occurred, so the event means "the cancellation was accepted", not "a pending job was removed".
unsubscribe, err := bus.Listen(schedule.TaskCanceled, recordCancellation)
if err != nil {
return err
}
compose.Defer(unsubscribe)
var TaskDeferred = event.NewTopic[TaskDeferredEvent]("schedule.task.deferred")
TaskDeferred is published when Scheduler.At or Scheduler.After has handed a job to the driver successfully. Failed calls publish nothing.
unsubscribe, err := bus.Listen(schedule.TaskDeferred, recordSubmission)
if err != nil {
return err
}
compose.Defer(unsubscribe)
Functions ¶
This section is empty.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder edits scheduler construction settings. New copies the final draft; retaining it cannot change the published scheduler or its registrations.
scheduler := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Logger(app.Logger())
})
func (*Builder) Events ¶
Events selects the shared bus for run and deferred-task outcomes. Nil publishes nothing. It replaces the previous bus and returns the same draft.
scheduler := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Events(app.Events())
})
func (*Builder) Logger ¶
Logger replaces the shared logger. A final nil uses slog.Default at construction. It returns the same draft and performs no logging.
scheduler := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Logger(app.Logger())
})
type BuilderFunc ¶
type BuilderFunc = func(*Builder)
BuilderFunc edits the fresh construction draft used by New. Callbacks run synchronously once in order; retaining the draft cannot reconfigure the published scheduler. A supplied nil callback panics.
Example:
policy := schedule.BuilderFunc(func(scheduler *schedule.Builder) {
scheduler.Logger(slog.Default())
})
scheduler := schedule.New(driver, policy)
type Dispatch ¶
Dispatch runs the entry or task called name. Drivers call it when an entry is due or a deferred job becomes due. Entries receive a nil payload. An error from Dispatch does not end Driver.Run; the driver logs it and may retry the job according to its engine.
dispatch := schedule.Dispatch(func(ctx context.Context, entryName string, payload []byte) error {
return execute(ctx, entryName, payload)
})
if err := driver.Run(ctx, entries, dispatch); err != nil {
return err
}
type Driver ¶
type Driver interface {
// Run calls dispatch whenever an entry in entries is due, and whenever a
// deferred job becomes due, until ctx is canceled or an error occurs.
// Cancellation of ctx is not an error: Run then returns nil. Run returns
// [ErrUnsupported] for an entry the driver cannot schedule, such as one
// in a time zone it cannot evaluate.
//
// if err := driver.Run(ctx, entries, dispatch); err != nil {
// return err
// }
Run(ctx context.Context, entries []Entry, dispatch Dispatch) error
// Defer stores job for later dispatch and returns its non-empty,
// distinct identifier. A job is dispatched by a running [Driver.Run],
// possibly in another process: Defer before Run is accepted, and a job
// whose time has passed is dispatched as soon as possible. A driver
// without support returns [ErrUnsupported].
//
// id, err := driver.Defer(ctx, job)
// if err != nil {
// return err
// }
// fmt.Println(id)
Defer(ctx context.Context, job Job) (string, error)
// Cancel removes the deferred job with the given identifier. An unknown or
// finished identifier is not an error.
//
// if err := driver.Cancel(ctx, id); err != nil {
// return err
// }
Cancel(ctx context.Context, id string) error
}
Driver decides when work runs. The Scheduler owns what runs; the driver owns timing, persistence, and coordination between processes. Execution drain, overlap coordination, and supported zones are driver-specific.
var driver schedule.Driver = memoryschedule.New() scheduler := schedule.New(driver) compose.Run(scheduler.Run)
type Entry ¶
type Entry struct {
// contains filtered or unexported fields
}
Entry is an immutable named function that runs on a Spec. Construct it with NewEntry; configuration belongs to EntryBuilder, not the published value. Its first declaration error is reported by Entry.Err.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
})
if err := entry.Err(); err != nil {
panic(err)
}
func NewEntry ¶
func NewEntry(entryName string, fn func(context.Context) error, configure ...EntryBuilderFunc) Entry
NewEntry creates an entry called entryName that runs fn. The name has 1-64 lowercase letters, digits, or hyphens, and does not start or end with a hyphen. A bad name is kept on the entry and reported by Entry.Err and Scheduler.Add as ErrInvalidName; a nil fn as ErrInvalidEntry. Set when it runs with EntryBuilder.When; omission never infers a schedule. Callbacks run directly once, synchronously in order on one fresh draft, even for invalid names or nil fn. Supplied nil callbacks and callback panics propagate; expanded nil or empty slices supply no callbacks. Final validation follows all callbacks. Publication copies settings, not fn or its captures.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
entry.Timeout(time.Hour)
})
if err := entry.Err(); err != nil {
panic(err)
}
Example ¶
ExampleNewEntry checks declaration errors and observes the completed policy. The execution function is stored, not invoked by construction.
package main
import (
"context"
"fmt"
"time"
"arkoren.dev/core/service/schedule"
)
func main() {
entry := schedule.NewEntry("report", func(context.Context) error {
return nil
}, func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Hour(3))
entry.Timeout(10 * time.Second)
})
if err := entry.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Println(entry.Name(), entry.Spec().Expression(), entry.TimeoutValue())
}
Output: report 0 3 * * * 10s
func (Entry) DescriptionValue ¶
DescriptionValue returns the description of the entry. Empty text is valid and has no execution semantics.
for _, entry := range scheduler.Entries() {
fmt.Println(entry.DescriptionValue())
}
func (Entry) Err ¶
Err returns the first error found while building the entry, or nil. A bad name wraps ErrInvalidName; a nil function, a bad spec or timeout, and a missing spec wrap ErrInvalidEntry. An entry without a spec is invalid.
entry := schedule.NewEntry("report", nil)
if err := entry.Err(); err != nil {
fmt.Println(errors.Is(err, schedule.ErrInvalidEntry))
}
func (Entry) Name ¶
Name returns the entry name. The identity remains unchanged after registration or execution.
for _, entry := range scheduler.Entries() {
fmt.Println(entry.Name())
}
func (Entry) Next ¶
Next returns the first run time strictly after the given time, or the zero time when the entry is invalid or nothing matches within five years.
after := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
for _, entry := range scheduler.Entries() {
fmt.Println(entry.Next(after))
}
func (Entry) Overlapping ¶
Overlapping reports whether a run may start while the previous run is still going. It is true unless EntryBuilder.WithoutOverlapping was used. Coordination belongs to the driver; manual RunNow execution bypasses it.
for _, entry := range scheduler.Entries() {
fmt.Println(entry.Name(), entry.Overlapping())
}
func (Entry) Spec ¶
Spec returns the spec that says when the entry runs. Transformations of the returned immutable value do not edit the entry.
for _, entry := range scheduler.Entries() {
fmt.Println(entry.Spec().Expression())
}
func (Entry) TimeoutValue ¶
TimeoutValue returns the bound on one run, or zero for no limit. It reports the configured cooperative deadline, not a forced termination.
for _, entry := range scheduler.Entries() {
fmt.Println(entry.Name(), entry.TimeoutValue())
}
type EntryBuilder ¶
type EntryBuilder struct {
// contains filtered or unexported fields
}
EntryBuilder configures one entry during NewEntry. Settings return the same draft and preserve its first error. Retaining a draft does not permit changes to an already published entry. It is not safe for concurrent use.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
entry.WithoutOverlapping()
})
if err := entry.Err(); err != nil {
panic(err)
}
func (*EntryBuilder) Description ¶
func (entry *EntryBuilder) Description(text string) *EntryBuilder
Description replaces the human-readable description and returns the same draft. Empty text clears it; this setting does not change any earlier error.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
entry.Description("Nightly report")
})
if err := entry.Err(); err != nil {
panic(err)
}
func (*EntryBuilder) Timeout ¶
func (entry *EntryBuilder) Timeout(duration time.Duration) *EntryBuilder
Timeout bounds one run and returns the same draft. Zero means no limit (also the default); a negative duration records an error. An earlier error prevents this setting from changing the draft. Cancellation is cooperative: a function must observe its context to stop. Drivers can detach scheduled execution from runner cancellation while draining. A positive timeout then remains an independent execution deadline; zero does not impose a shutdown drain bound. RunNow retains caller cancellation.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
entry.Timeout(time.Hour)
})
if err := entry.Err(); err != nil {
panic(err)
}
func (*EntryBuilder) When ¶
func (entry *EntryBuilder) When(spec Spec) *EntryBuilder
When replaces the run schedule and returns the same draft. Invalid specs record the first error immediately; a later valid spec cannot clear it. Spec is immutable, so later Spec transformations cannot change this draft.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
})
if err := entry.Err(); err != nil {
panic(err)
}
func (*EntryBuilder) WithoutOverlapping ¶
func (entry *EntryBuilder) WithoutOverlapping() *EntryBuilder
WithoutOverlapping asks the driver not to start a run while the previous run of the entry is still going. Overlap is allowed by default. It returns the same draft without changing any earlier error.
Example:
entry := NewEntry("report", func(context.Context) error {
return nil
}, func(entry *EntryBuilder) {
entry.When(UTC().Hour(3))
entry.WithoutOverlapping()
})
if err := entry.Err(); err != nil {
panic(err)
}
type EntryBuilderFunc ¶
type EntryBuilderFunc = func(*EntryBuilder)
EntryBuilderFunc edits the fresh declaration draft used by NewEntry. Callbacks run synchronously once in order, including invalid declarations; supplied nil callbacks panic. Entry.Err reports declaration errors.
Example:
policy := schedule.EntryBuilderFunc(func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Hour(3))
})
entry := schedule.NewEntry("cleanup", cleanup, policy)
if err := entry.Err(); err != nil {
return err
}
type Job ¶
type Job struct {
// Name is the name of the registered task to run.
Name string
// Payload is the JSON encoding of the task payload.
Payload []byte
// At is the time the job becomes due.
At time.Time
}
Job is a one-off deferred execution handed to Driver.Defer. It is a raw transport record, not a typed task definition. Drivers determine persistence and execution; the scheduler facade handles JSON encoding.
id, err := driver.Defer(ctx, schedule.Job{
Name: "remind",
Payload: []byte(`"hello"`),
At: due,
})
if err != nil {
return err
}
fmt.Println(id)
type RunFailedEvent ¶
type RunFailedEvent struct {
// Name is the entry or task name.
Name string
// Task reports whether the run was a deferred task rather than an entry.
Task bool
// Duration is how long the run took.
Duration time.Duration
// Err is the error the run returned, including a recovered panic or an
// exceeded timeout.
Err error
}
RunFailedEvent is the payload of RunFailed. It contains execution identity and timing, never task payload bytes. Error causes remain shared application values and can include sensitive details.
unsubscribe, err := bus.Listen(schedule.RunFailed, func(_ context.Context, outcome schedule.RunFailedEvent) error {
fmt.Println(outcome.Name, outcome.Duration)
return nil
})
if err != nil {
return err
}
compose.Defer(unsubscribe)
type RunSkippedEvent ¶
type RunSkippedEvent struct {
// Name is the entry or task name.
Name string
// Task reports whether the run was a deferred task rather than an entry.
Task bool
// Duration is how long the run took before it returned [ErrSkipped].
Duration time.Duration
}
RunSkippedEvent is the payload of RunSkipped. It describes an execution that chose to skip, not a driver's overlap guard suppressing invocation before the facade runs.
unsubscribe, err := bus.Listen(schedule.RunSkipped, func(_ context.Context, outcome schedule.RunSkippedEvent) error {
fmt.Println(outcome.Name, outcome.Task)
return nil
})
if err != nil {
return err
}
compose.Defer(unsubscribe)
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler registers entries and task handlers and hands them to a Driver, which decides when they run. Create one with New. Register before Run; manual RunNow execution is available independently.
scheduler := schedule.New(driver) fmt.Println(len(scheduler.Entries()))
func New ¶
func New(driver Driver, configure ...BuilderFunc) *Scheduler
New creates a Scheduler that delegates timing to driver. When telemetry is enabled, every run, scheduled or started with Scheduler.RunNow, emits one "schedule run" span, labeled with the entry or task name, and the arkoren.schedule.run.count and arkoren.schedule.run.duration metrics, and costs nothing otherwise. Cache, database and storage spans started with the run's context become children of the run span. Task payloads, error text and job identifiers are never recorded.
Callbacks run directly once in order on one fresh draft. Nil entries panic; expanded nil/empty slices omit edits. The final settings are independent of retained drafts; loggers, telemetry and event services remain shared.
sched := schedule.New(driver, func(scheduler *schedule.Builder) {
scheduler.Telemetry(app.Telemetry())
})
func (*Scheduler) Add ¶
Add registers entries. It adds all of them or none. It returns ErrInvalidName for a bad name, ErrInvalidEntry for any other invalid entry, ErrDuplicateName for a name that is already used, and ErrRunning after Scheduler.Run started. Entries in a non-UTC zone are checked for daylight saving transitions; see the package documentation.
if err := scheduler.Add(schedule.NewEntry("report", report, func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Hour(3))
})); err != nil {
return err
}
func (*Scheduler) After ¶
func (scheduler *Scheduler) After[T any](ctx context.Context, task Task[T], payload T, delay time.Duration) (string, error)
After defers task with payload until delay from now. See Scheduler.At. Zero or negative delay requests an execution due now or in the past; the driver's next opportunity determines when it actually runs.
id, err := scheduler.After(ctx, Remind, reminder, 10*time.Minute)
if err != nil {
return err
}
fmt.Println(id)
func (*Scheduler) At ¶
func (scheduler *Scheduler) At[T any](ctx context.Context, task Task[T], payload T, when time.Time) (string, error)
At defers task with payload until when and returns the job identifier from the driver. The task must be registered with Scheduler.Handle (ErrUnknownName otherwise) and when must not be zero. Payload encoding and driver errors retain their causes. A successful result means accepted for later execution, not that the task ran. Driver-specific cancellation and durability rules apply; no retry is automatic here.
id, err := scheduler.At(ctx, Remind, reminder, due)
if err != nil {
return err
}
fmt.Println(id)
func (*Scheduler) Cancel ¶
Cancel removes the deferred job with the given identifier. An unknown or finished identifier is not an error, and publishes TaskCanceled like any successful call, because the driver cannot say whether a job was removed. Driver errors are wrapped without publishing a success notification.
if err := scheduler.Cancel(ctx, id); err != nil {
return err
}
func (*Scheduler) Driver ¶
Driver returns the underlying Driver. Raw operations bypass the facade's execution registration and observations.
scheduler := schedule.New(driver) fmt.Println(scheduler.Driver() == driver)
func (*Scheduler) DriverAs ¶
DriverAs returns the first driver of type T in the chain of the underlying driver. A driver that wraps another exposes it with an Unwrap() Driver method, so wrappers do not hide the concrete driver.
if driver, ok := scheduler.DriverAs[*memoryschedule.Driver](); ok {
fmt.Printf("memory scheduling: %T\n", driver)
}
func (*Scheduler) Entries ¶
func (scheduler *Scheduler) Entries() collection.Slice[Entry]
Entries returns a copy of the registered entries in registration order. Replacing elements in the returned slice cannot edit registrations; each entry and its Spec are immutable values with shared execution captures. The eager collection is a snapshot, not a live query; the wrapper itself adds no ownership or copying beyond the detached slice returned here.
limited := scheduler.Entries().Filter(func(_ int, entry schedule.Entry) bool {
return entry.TimeoutValue() > 0
})
for _, entry := range limited {
fmt.Println(entry.Name(), entry.Spec().Expression())
}
func (*Scheduler) Handle ¶
Handle registers fn as the handler of task. It returns ErrInvalidName for a bad task name, ErrInvalidEntry for a nil fn, ErrDuplicateName when the name is already used and ErrRunning after Scheduler.Run started.
task := schedule.NewTask[string]("remind")
if err := scheduler.Handle(task, func(ctx context.Context, text string) error {
return sendReminder(ctx, text)
}); err != nil {
return err
}
func (*Scheduler) MCPTools ¶
MCPTools returns live entries and manual-run tools for explicit registration. A nonempty prefix produces prefix.entries and prefix.run in that CLI group; an empty prefix produces entries and run in the schedule CLI group. Tool Err reports invalid names. No authentication, policy, or registration is implicit.
entries only reads configuration. run executes application code once and waits through RunNow, preserving cancellation and entry timeouts. As with RunNow, driver-owned overlap guards do not apply to manual execution. Callers must not automatically retry it. Unknown names return a safe not_found ToolFailure; other errors retain their identity for adapter redaction. The caller must protect this capability with its own availability policy.
Example:
tools := scheduler.MCPTools("scheduler")
if err := tools[0].Err(); err != nil {
return err
}
result, err := tools[0].Call(ctx, []byte(`{}`))
if err != nil {
return err
}
fmt.Println(string(result))
func (*Scheduler) Run ¶
Run hands the registered entries to the driver and blocks until ctx is canceled or the driver fails. Registration is closed once Run starts, and a Scheduler runs only once: a second call returns ErrRunning. In-flight execution and drain semantics belong to the driver. In particular, memoryschedule stops admission on cancellation but waits without a drain timeout for detached executions to finish. No runner can forcibly stop Go code.
compose.Run(scheduler.Run)
func (*Scheduler) RunNow ¶
RunNow runs the entry called name immediately, with the entry timeout, panic recovery, and logging of a scheduled run. It returns ErrUnknownName when no entry has that name. An application error can also wrap ErrUnknownName; the error alone does not distinguish failed lookup from a nested scheduling operation's failure. RunNow preserves caller cancellation and bypasses driver-owned overlap guards.
if err := scheduler.RunNow(ctx, "report"); err != nil {
return err
}
type Spec ¶
type Spec struct {
// contains filtered or unexported fields
}
Spec describes when an Entry runs. It is an immutable value: every method returns a modified copy, and the first error is kept and reported by Spec.Err. Start one with UTC or In; the zero Spec has no time zone and is invalid.
Time fields (second, minute, hour) that are not set default to 0 when they are finer than the coarsest field that is set, and to every value when they are coarser. A spec with date fields but no time fields runs at midnight; a zone alone, such as UTC(), is invalid because it declares no schedule. Entry publication preserves these immutable Spec rules.
Example:
spec := schedule.UTC().Day(1)
if err := spec.Err(); err != nil {
return err
}
fmt.Println(spec.Expression()) // 0 0 1 * *
func In ¶
In starts a spec that reads its fields in location. A nil location is an error. Zones with daylight saving time skip a time inside the spring gap and run once inside the autumn overlap; see the package documentation. The location remains shared, and transformations return independent Specs.
location, err := time.LoadLocation("Europe/Amsterdam")
if err != nil {
return err
}
spec := schedule.In(location).Weekdays().Hour(9)
if err := spec.Err(); err != nil {
return err
}
func UTC ¶
func UTC() Spec
UTC starts a spec that reads its fields in UTC. A zone alone is not a schedule; add a calendar field before registration.
spec := schedule.UTC().Hour(3)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Cron ¶
Cron sets a raw cron expression: five fields, or six with seconds first. Each field accepts *, n, a,b, a-b, */n, and a-b/n, with numbers only. Day of week is 0-6 from Sunday. When both day of month and day of week are restricted, either may match. It cannot be combined with field methods. A step larger than a range selects only its first value. Invalid text is retained as the first Err; a later valid expression cannot clear it.
spec := schedule.UTC().Cron("0 */6 * * *")
if err := spec.Err(); err != nil {
return err
}
func (Spec) Day ¶
Day sets the days of the month, 1-31, on which the spec matches. It cannot be combined with Spec.On, Spec.Weekdays, or Spec.Weekends. Impossible dates are skipped rather than normalized into another month.
spec := schedule.UTC().Day(31)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Err ¶
Err returns the first error found while building the spec, or nil. Errors wrap ErrInvalidEntry. An unset zone or a zone with no fields is invalid even without a stored error.
spec := schedule.UTC().Hour(25)
if err := spec.Err(); err != nil {
fmt.Println(errors.Is(err, schedule.ErrInvalidEntry))
}
func (Spec) Every ¶
Every matches at a fixed step. The unit of the step is seconds when duration is under a minute, minutes when it is under an hour, and hours otherwise. Fields finer than the unit are 0; coarser fields match every value unless set. The duration must be a whole number of its unit that divides 60 (seconds and minutes) or 24 (hours) evenly, and under 24 hours. This is an aligned calendar cadence, not a delay measured from construction.
spec := schedule.UTC().Every(5 * time.Minute)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Expression ¶
Expression returns the compiled cron expression: five fields, or six with seconds first when seconds other than 0 are needed. It is empty when the spec is invalid. Call Err when an empty expression must be distinguished from a valid one.
spec := schedule.UTC().Day(1)
if err := spec.Err(); err != nil {
return err
}
fmt.Println(spec.Expression()) // 0 0 1 * *
func (Spec) HasSeconds ¶
HasSeconds reports whether Spec.Expression has a seconds field. Invalid specs return false; inspect Err before relying on the result.
spec := schedule.UTC().Second(30)
if err := spec.Err(); err != nil {
return err
}
fmt.Println(spec.HasSeconds()) // true
func (Spec) Hour ¶
Hour sets the hours, 0-23, at which the spec matches. Values are copied into immutable text; empty or invalid input retains an error. Unset minutes and seconds default to zero.
spec := schedule.UTC().Hour(3, 15)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Location ¶
Location returns the time zone the spec is read in. It is nil for a zero Spec or a spec built with a nil location. The returned location is shared rather than copied.
spec := schedule.UTC().Hour(3) fmt.Println(spec.Location() == time.UTC)
func (Spec) Minute ¶
Minute sets the minutes, 0-59, at which the spec matches. Empty input, out-of-range values, or a duplicate setting retain an error. Finer unset time fields default to zero.
spec := schedule.UTC().Minute(15, 45)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Month ¶
Month sets the months in which the spec matches. Only January through December are valid; an empty list retains an error. With no time fields, the schedule matches at midnight.
spec := schedule.UTC().Month(time.January, time.July).Day(1)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Next ¶
Next returns the first matching time strictly after the given time. It returns the zero time when the spec is invalid or nothing matches within five years. It skips nonexistent wall times and chooses the first occurrence of an overlap. This computes timing only; it does not start work or mutate Spec.
after := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) spec := schedule.UTC().Hour(3) fmt.Println(spec.Next(after).IsZero()) // false
Example ¶
ExampleSpec_Next computes a deterministic calendar instant without timers. Next is strictly after the supplied time and does not start execution.
package main
import (
"fmt"
"time"
"arkoren.dev/core/service/schedule"
)
func main() {
spec := schedule.UTC().Hour(3)
if err := spec.Err(); err != nil {
fmt.Println(err)
return
}
after := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(spec.Next(after).Format(time.RFC3339))
}
Output: 2026-01-01T03:00:00Z
func (Spec) On ¶
On sets the days of the week on which the spec matches. It cannot be combined with Spec.Day. An empty list or values outside Sunday through Saturday retain an error.
spec := schedule.UTC().On(time.Monday, time.Thursday).Hour(9)
if err := spec.Err(); err != nil {
return err
}
func (Spec) Second ¶
Second sets the seconds, 0-59, at which the spec matches. Values are sorted and deduplicated without retaining the input slice. Empty input, out-of-range values, or setting the field twice make Err non-nil.
spec := schedule.UTC().Second(0, 30)
if err := spec.Err(); err != nil {
return err
}
type Task ¶
type Task[T any] struct { // contains filtered or unexported fields }
Task names one kind of deferred job and fixes the payload type T it carries. Create it with NewTask and register its handler with Scheduler.Handle. Names share the entry namespace. Construction does not validate or register a handler; Handle checks the portable identifier and payload type binding.
task := schedule.NewTask[string]("remind")
if err := scheduler.Handle(task, remind); err != nil {
return err
}
func NewTask ¶
NewTask returns the task called name that carries payloads of type T. The name shares one namespace with Entry names. Validation is deferred to Handle; At requires that handler to be registered. Definitions sharing one name must also agree on their payload type.
task := schedule.NewTask[string]("remind")
fmt.Println(task.Name()) // remind
type TaskCanceledEvent ¶
type TaskCanceledEvent struct {
// ID is the job identifier passed to [Scheduler.Cancel].
ID string
}
TaskCanceledEvent is the payload of TaskCanceled. It reports a successful cancellation request, not proof that work existed or that an already-running handler stopped.
unsubscribe, err := bus.Listen(schedule.TaskCanceled,
func(_ context.Context, outcome schedule.TaskCanceledEvent) error {
fmt.Println(outcome.ID)
return nil
})
if err != nil {
return err
}
compose.Defer(unsubscribe)
type TaskDeferredEvent ¶
type TaskDeferredEvent struct {
// Name is the task name.
Name string
// ID is the job identifier the driver returned, usable with
// [Scheduler.Cancel].
ID string
// At is when the job is due to run.
At time.Time
}
TaskDeferredEvent is the payload of TaskDeferred. It never carries the task payload, which may hold personal data. Acceptance is not a completion or durability guarantee; those belong to the selected driver and the task's application effect.
unsubscribe, err := bus.Listen(schedule.TaskDeferred,
func(_ context.Context, outcome schedule.TaskDeferredEvent) error {
fmt.Println(outcome.Name, outcome.At)
return nil
})
if err != nil {
return err
}
compose.Defer(unsubscribe)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
calendar
Package calendar compiles bounded cron calendars and resolves wall times.
|
Package calendar compiles bounded cron calendars and resolves wall times. |
|
Package memoryschedule provides an in-process schedule.Driver for local development and single-replica deployments.
|
Package memoryschedule provides an in-process schedule.Driver for local development and single-replica deployments. |
|
Package scheduletest helps test code that defers jobs and checks drivers of the schedule package.
|
Package scheduletest helps test code that defers jobs and checks drivers of the schedule package. |