taskx

package
v0.4.11 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRuntimeUnavailable = errors.New("taskx: runtime unavailable")
	ErrHandlerExists      = errors.New("taskx: handler already registered")
)
View Source
var (
	ErrAlreadyStarted   = errors.New("taskx: scheduler already started")
	ErrNotStarted       = errors.New("taskx: scheduler not started")
	ErrJobAlreadyExists = errors.New("taskx: job already exists")
	ErrJobNotFound      = errors.New("taskx: job not found")
	ErrInvalidJob       = errors.New("taskx: invalid job")
	ErrLeaseNotAcquired = errors.New("taskx: distributed lease not acquired")
	ErrLeaseLost        = errors.New("taskx: distributed lease lost")
)

Functions

This section is empty.

Types

type DeliveryFailureMode

type DeliveryFailureMode string

DeliveryFailureMode controls what the runtime does when the application callback returns an error.

const (
	DeliveryFailureConstant DeliveryFailureMode = "constant"
	DeliveryFailureDrop     DeliveryFailureMode = "drop"
)

type DeliveryFailurePolicy

type DeliveryFailurePolicy struct {
	Mode       DeliveryFailureMode
	MaxRetries *uint32
	Interval   time.Duration
}

DeliveryFailurePolicy is deliberately smaller than the local RetryPolicy. It governs delivery from the runtime to the application, not retries inside a business handler.

func (DeliveryFailurePolicy) Validate

func (p DeliveryFailurePolicy) Validate() error

type Event

type Event struct {
	Kind        EventKind
	JobName     string
	RunID       string
	ScheduledAt time.Time
	Timestamp   time.Time
	Attempt     int
	MaxAttempts int
	Duration    time.Duration
	Reason      string
	Err         error
}

Event is emitted for observability adapters.

type EventHandler

type EventHandler func(context.Context, TriggerEvent) error

EventHandler handles one durable runtime trigger.

type EventKind

type EventKind string

EventKind identifies scheduler lifecycle and execution events.

const (
	EventScheduled EventKind = "scheduled"
	EventStarted   EventKind = "started"
	EventRetrying  EventKind = "retrying"
	EventSucceeded EventKind = "succeeded"
	EventFailed    EventKind = "failed"
	EventSkipped   EventKind = "skipped"
)

type Handler

type Handler func(context.Context) error

Handler is a unit of background work. Implementations must be idempotent because retries and failover can result in at-least-once execution.

type Job

type Job struct {
	Name         string
	Schedule     Schedule
	Handler      Handler
	RunOnStart   bool
	AllowOverlap bool
	Timeout      time.Duration
	Retry        RetryPolicy
	Lease        LeaseOptions
}

Job describes a scheduled background task.

type Lease

type Lease interface {
	Renew(ctx context.Context, ttl time.Duration) error
	Release(ctx context.Context) error
}

Lease is an owned distributed lock. Renew and Release must verify ownership.

type LeaseOptions

type LeaseOptions struct {
	Enabled       bool
	Key           string
	TTL           time.Duration
	RenewInterval time.Duration
}

LeaseOptions enables cross-instance singleton execution.

type Locker

type Locker interface {
	TryAcquire(ctx context.Context, key string, ttl time.Duration) (lease Lease, acquired bool, err error)
}

Locker coordinates a job run across service replicas.

type ManagedJob

type ManagedJob struct {
	Name          string
	Schedule      string
	DueTime       string
	Repeats       *uint32
	TTL           string
	Data          []byte
	DataTypeURL   string
	Overwrite     bool
	FailurePolicy *DeliveryFailurePolicy
}

ManagedJob is a durable job definition stored by an external task runtime. Schedule uses Kernel's canonical scheduler expression format:

  • @every 5m
  • @hourly, @daily, @weekly, @monthly, @yearly
  • six-field cron: seconds minutes hours day-of-month month day-of-week

DueTime and TTL accept RFC3339 timestamps or Go duration strings. At least one of Schedule or DueTime must be set.

func (ManagedJob) Validate

func (j ManagedJob) Validate() error

type Observer

type Observer interface {
	Observe(context.Context, Event)
}

Observer receives task execution events. Implementations must be non-blocking or perform their own buffering.

type ObserverFunc

type ObserverFunc func(context.Context, Event)

ObserverFunc adapts a function to Observer.

func (ObserverFunc) Observe

func (f ObserverFunc) Observe(ctx context.Context, event Event)

type Option

type Option func(*Scheduler)

Option configures Scheduler.

func WithLocker

func WithLocker(locker Locker) Option

WithLocker enables distributed singleton jobs.

func WithNow

func WithNow(now func() time.Time) Option

WithNow overrides the clock used for schedule calculations and tests.

func WithObserver

func WithObserver(observer Observer) Option

WithObserver attaches logging, metrics, tracing, or audit adapters.

type PrometheusObserver

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

PrometheusObserver exports bounded-cardinality task execution metrics.

func NewPrometheusObserver

func NewPrometheusObserver(reg prometheus.Registerer) (*PrometheusObserver, error)

NewPrometheusObserver registers taskx metrics with reg. Create one observer per registry and share it across schedulers in the same process.

func (*PrometheusObserver) Observe

func (o *PrometheusObserver) Observe(_ context.Context, event Event)

type RedisLocker

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

RedisLocker implements distributed leases with SET NX and ownership-checked Lua scripts. The scripts use one key and are safe for Redis Cluster slots.

func NewRedisLocker

func NewRedisLocker(client redis.UniversalClient, prefix string) *RedisLocker

NewRedisLocker creates a Redis-backed Locker. Empty prefix uses the Kernel default namespace.

func (*RedisLocker) TryAcquire

func (l *RedisLocker) TryAcquire(ctx context.Context, key string, ttl time.Duration) (Lease, bool, error)

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts    int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
	Multiplier     float64
}

RetryPolicy controls retries for one scheduled run. MaxAttempts includes the first attempt. Zero values disable retries.

type Runtime

type Runtime interface {
	Schedule(context.Context, ManagedJob) error
	Get(context.Context, string) (ManagedJob, error)
	Delete(context.Context, string) error
	RegisterHandler(string, EventHandler) error
}

Runtime is the provider-neutral contract for a durable task runtime.

A Runtime owns the schedule definition and dispatches trigger events back to one application replica. Implementations are expected to provide at-least-once delivery, therefore handlers must remain idempotent.

type Schedule

type Schedule interface {
	Next(after time.Time) time.Time
}

Schedule calculates the first execution strictly after the supplied time. Returning the zero time means that the schedule has completed.

func At

func At(at time.Time) Schedule

At returns a one-shot schedule.

func Every

func Every(interval time.Duration) Schedule

Every returns a fixed-rate schedule. Missed ticks are skipped rather than replayed when a service was stopped or a previous run took too long.

func ScheduleFunc

func ScheduleFunc(fn func(time.Time) time.Time) Schedule

ScheduleFunc adapts a function to Schedule. The function must return either zero or a time strictly after its argument.

type Scheduler

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

Scheduler owns registered jobs and their lifecycle.

func NewScheduler

func NewScheduler(opts ...Option) *Scheduler

NewScheduler creates a scheduler. Register all jobs before Start.

func (*Scheduler) Register

func (s *Scheduler) Register(job Job) error

Register adds a job. Registration after Start is intentionally rejected to keep service boot deterministic.

func (*Scheduler) Shutdown

func (s *Scheduler) Shutdown(ctx context.Context) error

Shutdown stops scheduling, cancels active handlers, and waits for exit.

func (*Scheduler) Start

func (s *Scheduler) Start(parent context.Context) error

Start begins scheduling and returns immediately.

func (*Scheduler) Trigger

func (s *Scheduler) Trigger(ctx context.Context, name string) error

Trigger executes a registered job immediately while preserving singleton, retry, timeout, lease, and observability behavior.

type TriggerEvent

type TriggerEvent struct {
	Name string
	Data []byte
}

TriggerEvent is delivered by a Runtime when a managed job becomes due.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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