Documentation
¶
Overview ¶
Package scheduler wraps robfig/cron/v3 for running periodic background jobs with panic-safe execution, per-job overlap policies, and observable statistics.
Scope: single-instance deployments. Distributed locking and multi-node coordination are intentionally out of scope.
Execution pipeline for cron-triggered jobs:
cron schedule -> Policy (Delay / Skip) -> Recover -> execute -> Job.Run
Policy is outer so it always observes a clean return from its wrapped chain and its internal bookkeeping (mutex unlock / channel refill) is never skipped by a panic. execute() additionally has its own defer recover so that RunNow (which bypasses the chain) is equally safe and so that panic is accounted for in statistics.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrBusy = errors.New("scheduler: job busy")
ErrBusy signals that a Job refused to run because its own concurrency guard rejected the call (an instance is already in progress).
execute treats ErrBusy as neither success nor failure: RunCount and FailCount are unchanged, LastErr is not overwritten, and only a Debug log line is emitted. Return ErrBusy directly, or wrap it with fmt.Errorf("...: %w", ErrBusy); both forms are recognised via errors.Is.
var ErrPoolStopped = errors.New("pool: stopped")
ErrPoolStopped is returned by Submit when the Pool has been stopped.
Functions ¶
This section is empty.
Types ¶
type Entry ¶
type Entry struct {
Name string `json:"name"`
Spec string `json:"spec"`
Next time.Time `json:"next"`
LastStart time.Time `json:"last_start"`
LastEnd time.Time `json:"last_end"`
LastErr string `json:"last_err"`
RunCount int64 `json:"run_count"`
FailCount int64 `json:"fail_count"`
AvgDurMs int64 `json:"avg_dur_ms"`
}
Entry is an immutable snapshot of a Job's runtime state, intended for admin APIs and diagnostics.
type Job ¶
Job is the contract for anything registered with Scheduler.
Name must be unique within a Scheduler and is also the key for RunNow. Spec is any expression accepted by robfig/cron/v3 (e.g. "@every 1h", "0 */5 * * *"). Run must respect ctx cancellation; returning ErrBusy indicates "refused by internal guard" and is not counted as a failure.
type Policy ¶
type Policy int
Policy controls how the scheduler handles a cron trigger that fires while a previous run of the same Job is still in progress.
const ( // PolicyDelayIfRunning queues the new trigger until the previous run // finishes. Suitable for infrequent, must-not-skip tasks. PolicyDelayIfRunning Policy = iota // PolicySkipIfRunning drops the new trigger. Suitable for frequent // tasks where missing an occasional tick is acceptable. PolicySkipIfRunning )
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is a bounded worker pool for one-off async tasks. It fills the gap between cron-scheduled jobs (Scheduler) and unmanaged goroutines.
Submitted tasks run on a fixed set of worker goroutines. Panics are recovered and logged. Stop drains the queue and waits for in-flight tasks, integrating cleanly with the Component shutdown sequence.
func NewPool ¶
func NewPool(opts PoolOptions) *Pool
NewPool creates a Pool but does not start workers. Call Start to begin processing. Intended to be wrapped by a PoolComponent that wires the lifecycle into the Registry.
func (*Pool) Start ¶
Start launches worker goroutines. The parent context is used to derive a cancellable context — Stop() cancels it, signalling workers to wind down after draining. Start is idempotent — the second call is a no-op.
func (*Pool) Stop ¶
Stop signals workers to drain and waits for all in-flight tasks to complete. Stop is idempotent — the second call waits for the same drain without panicking. Returns ctx.Err() if the deadline is exceeded.
func (*Pool) Submit ¶
Submit enqueues a task for async execution. It blocks when the queue is full or returns an error when ctx is cancelled. Submit is safe to call from any goroutine. Returns ErrPoolStopped after Stop is called.
Uses recover to handle the inherent TOCTOU race between Submit and Stop: if Stop closes the channel between our check and the send, the panic is caught and converted to ErrPoolStopped.
type PoolOptions ¶
type PoolOptions struct {
// Workers is the number of concurrent worker goroutines. Default 10.
Workers int
// QueueSize is the buffered channel capacity. When the queue is full,
// Submit blocks until a slot opens or ctx is cancelled. Default 1000.
QueueSize int
// Logger receives task start/completion/error/panic events.
Logger log.Logger
}
PoolOptions configures a Pool.
type PoolStats ¶
type PoolStats struct {
Submitted int64 `json:"submitted"`
Completed int64 `json:"completed"`
Failed int64 `json:"failed"`
Panicked int64 `json:"panicked"`
Pending int `json:"pending"` // current queue depth
InFlight int64 `json:"in_flight"`
}
PoolStats is a snapshot of pool runtime statistics.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler runs registered Jobs on their cron schedules.
func New ¶
New constructs a Scheduler. The parent context governs job execution; Stop() cancels the derived root context, signalling all in-flight Run(ctx) invocations to wind down.
Uses the cron runner's default time zone (time.Local). Containerised deployments with TZ=UTC will see specs like "0 0 * * *" fire at UTC midnight; call NewWithLocation to pin an explicit zone.
func NewWithLocation ¶
NewWithLocation constructs a Scheduler with an explicit time.Location. All cron specs are interpreted in this zone. Typical use: a web app with users spread across zones picks a business zone (e.g. "America/ New_York") so operator-facing specs line up with invoices/reports.
func (*Scheduler) Register ¶
Register adds a Job. An invalid spec returns an error and leaves internal state untouched. Duplicate names are rejected.
func (*Scheduler) RunNow ¶
RunNow synchronously executes the named Job once, outside the cron schedule. It respects the Job's Policy: with PolicySkipIfRunning, RunNow returns ErrBusy when a concurrent run is in progress; with PolicyDelayIfRunning, RunNow blocks until the in-flight run completes. Panic recovery and statistics bookkeeping match scheduled runs.
Returns the Job's error (or wrapped panic) if the run executed. When PolicySkipIfRunning rejects execution, returns ErrBusy (which is classified as "busy, not failure" and not counted in FailCount).
type Task ¶
type Task struct {
// Name identifies the task in logs and metrics. Not required to be
// unique — multiple tasks with the same name are allowed.
Name string
// Run executes the task. The context is cancelled when the Pool is
// stopped; long-running tasks should check ctx.Done().
Run func(ctx context.Context) error
}
Task is a named unit of work submitted to a Pool.