Documentation
¶
Overview ¶
Package worker provides background task management for Credo applications.
It unifies continuous workers (queue consumers, watchers, processors) and scheduled workers (cron-style maintenance jobs) under a single registration and lifecycle model.
Quick Start ¶
worker.MustRegister(app, worker.Func("heartbeat", func(ctx context.Context) error {
<-ctx.Done()
return nil
}))
worker.MustRegister(app, cleanup,
worker.WithSchedule("@every 5m"),
worker.WithStartImmediately(),
)
Adapted From ¶
Cron expression parsing and next-fire calculation are adapted from robfig/cron v3 (MIT). See NOTICES for full attribution.
Maturity: beta
Index ¶
- Constants
- func Attempt(ctx context.Context) int
- func MustRegister(app *credo.App, w Worker, opts ...Option)
- func Register(app *credo.App, w Worker, opts ...Option) error
- func RunID(ctx context.Context) string
- func ScheduledAt(ctx context.Context) time.Time
- func WorkerName(ctx context.Context) string
- type Definition
- type Info
- type Option
- type Pool
- type ReadinessPolicy
- type Schedule
- type Status
- type Worker
Constants ¶
const DefaultRestartDelay = 3 * time.Second
DefaultRestartDelay is the default delay between continuous worker restarts.
Variables ¶
This section is empty.
Functions ¶
func MustRegister ¶
MustRegister is like Register but panics on error.
func Register ¶
Register adds w to the application's worker pool.
Workers are started during credo.App.Run and stopped during credo.App.Shutdown. Register must be called before the app is finalized or run. Use MustRegister when bootstrap code should fail fast by panicking.
func ScheduledAt ¶
ScheduledAt returns the intended fire time for scheduled workers.
func WorkerName ¶
WorkerName returns the worker name stored in ctx.
Types ¶
type Definition ¶
type Definition struct {
// contains filtered or unexported fields
}
Definition is the immutable configuration of a registered worker.
func (*Definition) Kind ¶
func (d *Definition) Kind() string
Kind reports whether the worker is continuous or scheduled.
type Info ¶
type Info struct {
Name string
Kind string
Schedule string
Status Status
Attempts int64 // restart count for continuous workers; consecutive failures for scheduled workers.
LastRun time.Time
LastSuccess time.Time // completion time of the last run that returned nil; zero until then
LastError string
}
Info is a point-in-time snapshot of a worker's state.
type Option ¶
type Option func(*options)
Option configures worker registration.
func WithMaxConsecutiveFailures ¶
WithMaxConsecutiveFailures sets the failure threshold for scheduled workers. Zero (the default) means unlimited failures; the worker is marked failed only once a positive limit is reached.
func WithMaxRestarts ¶
WithMaxRestarts sets the maximum restart count for continuous workers. Zero (the default) means unlimited restarts; the worker is marked failed only once a positive limit is reached.
func WithReadiness ¶ added in v0.16.0
func WithReadiness(policy ReadinessPolicy) Option
WithReadiness binds the worker to the readiness probe under policy. Registration fails when the policy has no condition, when MaxSuccessAge is negative, or when a scheduled-only condition is used on a continuous worker.
func WithRestartDelay ¶
WithRestartDelay sets the delay between continuous worker restarts. A zero delay is treated as the default (DefaultRestartDelay) to avoid busy-looping a worker that fails immediately on every run.
func WithSchedule ¶
WithSchedule makes the worker scheduled using a cron expression.
func WithStartImmediately ¶
func WithStartImmediately() Option
WithStartImmediately runs a scheduled worker once during startup.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool manages registered workers and integrates with app lifecycle.
func (*Pool) Shutdown ¶
Shutdown stops all workers and waits for them to exit. The first call cancels the pool context and starts the wait; every call, including a concurrent or later one, returns nil once all workers have returned — completion takes precedence over an already-ended ctx — and ctx.Err() only while workers are still running when ctx ends. A pool that was never started shuts down immediately, and Start is refused afterwards.
type ReadinessPolicy ¶ added in v0.16.0
type ReadinessPolicy struct {
// RequireFirstSuccess keeps the instance unready until the worker's first
// run has completed without error — a startup barrier for recovery or
// warm-up jobs. Scheduled workers only; pair it with [WithStartImmediately]
// unless waiting for the first cron activation is intended. Once satisfied
// it stays satisfied, even if later runs fail.
RequireFirstSuccess bool
// FailWhenFailed reports the instance unready once the worker reaches
// [StatusFailed], that is, once it exhausted [WithMaxRestarts] or
// [WithMaxConsecutiveFailures]. Use it only for workers the instance cannot
// serve without: every replica hitting the same persistent failure leaves
// rotation together.
FailWhenFailed bool
// MaxSuccessAge reports the instance unready when the last successful run
// finished longer ago than this duration. Scheduled workers only; zero
// disables the check. Until the first success it is not applied — combine
// it with RequireFirstSuccess to close that window.
MaxSuccessAge time.Duration
}
ReadinessPolicy describes how one worker contributes to the application's readiness probe (see credo.App.UseHealth). Every condition is opt-in and the zero policy is rejected by WithReadiness; a worker with no policy never influences readiness, because not every failed worker should take an instance out of rotation.
The contribution is reported as a readiness check named "worker:<name>", next to checks added with credo.App.AddReadinessCheck. It is evaluated in-memory from the worker's last known state and never blocks. Registration order relative to UseHealth does not matter.
type Schedule ¶
type Schedule struct {
// contains filtered or unexported fields
}
Schedule represents a compiled cron schedule.
func ParseSchedule ¶
ParseSchedule parses a cron expression into a compiled schedule.
The supported syntax is standard 5-field Vixie cron — minute, hour, day-of-month, month, day-of-week — with lists ("1,15"), ranges ("1-5"), steps ("*/10", "8-18/2"), month and weekday names ("jan", "sat"), "?" as an alias for "*", and 7 accepted as Sunday. The descriptors @hourly, @daily (alias @midnight), @weekly, @monthly, and "@every <duration>" are also accepted. Schedules are evaluated in the server's local time zone and fire at second 0 of the matching minute; for sub-minute periods use "@every <duration>".
As in crontab(5), when both the day-of-month and day-of-week fields are restricted (neither is "*"), the schedule fires when EITHER matches: "0 0 13 * fri" runs on the 13th of the month AND on every Friday. Note that a step applied to "*" (e.g. "*/2" in day-of-month) counts as restricted for this rule.
type Status ¶
type Status string
Status represents a worker's current lifecycle state.
const ( // StatusIdle means the worker is registered but not yet started. StatusIdle Status = "idle" // StatusRunning means the worker is actively executing. StatusRunning Status = "running" // StatusWaiting means the worker is waiting for restart delay or next tick. StatusWaiting Status = "waiting" // StatusStopped means the worker exited normally and will not run again. StatusStopped Status = "stopped" // StatusFailed means the worker exceeded its configured failure threshold. StatusFailed Status = "failed" )