worker

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 13 Imported by: 0

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: experimental

Index

Constants

View Source
const DefaultRestartDelay = 3 * time.Second

DefaultRestartDelay is the default delay between continuous worker restarts.

Variables

This section is empty.

Functions

func Attempt

func Attempt(ctx context.Context) int

Attempt returns the current worker attempt stored in ctx.

func MustRegister

func MustRegister(app *credo.App, w Worker, opts ...Option)

MustRegister is like Register but panics on error.

func Register

func Register(app *credo.App, w Worker, opts ...Option) error

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 RunID

func RunID(ctx context.Context) string

RunID returns the execution identifier stored in ctx.

func ScheduledAt

func ScheduledAt(ctx context.Context) time.Time

ScheduledAt returns the intended fire time for scheduled workers.

func WorkerName

func WorkerName(ctx context.Context) string

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

func WithMaxConsecutiveFailures(n int) Option

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

func WithMaxRestarts(n int) Option

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 WithRestartDelay

func WithRestartDelay(d time.Duration) Option

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

func WithSchedule(expr string) Option

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

func (p *Pool) Shutdown(ctx context.Context) error

Shutdown stops all workers and waits for them to exit.

func (*Pool) Start

func (p *Pool) Start(ctx context.Context) error

Start launches registered workers.

func (*Pool) Workers

func (p *Pool) Workers() []Info

Workers returns a snapshot of registered worker state.

type Schedule

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

Schedule represents a compiled cron schedule.

func ParseSchedule

func ParseSchedule(expr string) (*Schedule, error)

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.

func (*Schedule) Next

func (s *Schedule) Next(now time.Time) time.Time

Next returns the next fire time after now.

func (*Schedule) String

func (s *Schedule) String() string

String returns the original cron expression.

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

type Worker

type Worker interface {
	// Name returns the worker's unique registration name.
	Name() string
	// Run executes the worker's logic.
	Run(ctx context.Context) error
}

Worker defines a background task managed by the framework.

func Func

func Func(name string, fn func(ctx context.Context) error) Worker

Func adapts a plain function into a Worker.

Jump to

Keyboard shortcuts

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