periodic

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package periodic is a tiny in-process scheduler. It runs a function on a recurring interval, with two niceties that a raw time.Ticker can't do:

  • RetryInterval: when the function returns an error, the next wakeup uses this shorter cadence so a transient failure (DNS blip, upstream 503) recovers fast without spamming. After the next success the schedule snaps back to Interval.
  • Jitter: ±N added to every wakeup so N service replicas don't all hit the same upstream at the exact same second.

Internally it uses time.Timer with Reset(), not time.Ticker — Ticker has a fixed cadence by design and can't accommodate the retry-on-error path. From the caller's POV the behaviour is ticker-like: register a job, it runs forever in a goroutine until ctx is cancelled.

One job per Run call. To register many, call it many times — each spawns its own goroutine. There's no central registry by design: bookkeeping should live with the consumer.

periodic.Run(ctx, periodic.Job{
    Name:          "cf_cidrs_refresh",
    Interval:      24 * time.Hour,
    RetryInterval: 1 * time.Hour,
    Jitter:        30 * time.Minute,
    Fn:            cidrSet.Refresh,
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, j Job)

Run starts the goroutine and returns immediately. The goroutine runs until ctx is cancelled. No way to deregister a single job — cancel ctx (which the caller probably bound to SIGTERM) to stop everything together.

Types

type Batcher

type Batcher[T any] struct {
	// contains filtered or unexported fields
}

Batcher coalesces high-frequency items into periodic bulk flushes. Producers call Add (best-effort: it never wedges the producer once shutdown begins); a single Run goroutine drains the buffer to Flush either when it reaches MaxBatch items or every Interval, whichever comes first. On ctx cancellation Run drains whatever is still buffered with one final Flush before returning, so a graceful shutdown does not lose the in-memory batch.

It is the write-coalescing companion to Run (this file's sibling): a stream that produces thousands of items/second but whose sink (Mongo, an HTTP API) wants a handful of bulk writes/minute feeds a Batcher instead of writing per item.

b := periodic.NewBatcher(periodic.BatcherConfig[Domain]{
    Name:     "domain_upsert",
    Interval: 10 * time.Second,
    MaxBatch: 500,
    Flush:    store.UpsertDomains,
})
go b.Run(ctx)        // one draining goroutine
b.Add(ctx, domain)   // from the producer(s)

func NewBatcher

func NewBatcher[T any](cfg BatcherConfig[T]) *Batcher[T]

NewBatcher builds a Batcher from cfg, applying defaults for the unset fields. It does not start anything: call Run in a goroutine.

func (*Batcher[T]) Add

func (b *Batcher[T]) Add(ctx context.Context, item T)

Add hands an item to the batcher. It blocks only until the buffered channel has room or ctx is cancelled (then the item is dropped), so it never wedges the producer after shutdown begins. Safe for concurrent producers.

func (*Batcher[T]) Run

func (b *Batcher[T]) Run(ctx context.Context)

Run is the single draining goroutine. It returns when ctx is cancelled, after a final flush of whatever is still buffered.

type BatcherConfig

type BatcherConfig[T any] struct {
	// Name labels the batcher in flush log records (`name=…`).
	Name string

	// Interval is the maximum time an item waits before its batch is
	// flushed. A flush also fires early when MaxBatch is reached.
	Interval time.Duration

	// MaxBatch flushes the buffer early once it holds this many items,
	// bounding both flush size and the memory the buffer can hold.
	MaxBatch int

	// BufferSize is the channel capacity between producers and the Run
	// goroutine. Zero defaults to MaxBatch*4 so a brief producer burst
	// does not block while a flush is in flight.
	BufferSize int

	// FlushTimeout caps a single Flush call. Zero defaults to 30s. Each
	// flush runs under a fresh background-derived context so the final
	// shutdown drain still completes after the caller's ctx is cancelled.
	FlushTimeout time.Duration

	// Flush writes one batch to the sink. A non-nil error is logged and
	// the batch is dropped (the items are gone); make Flush idempotent
	// and tolerant of partial failure (e.g. duplicate-safe upserts).
	Flush func(ctx context.Context, items []T) error

	// Logger records flush OK / error events. nil = log.Default.
	Logger logger
}

BatcherConfig configures a Batcher. Name, Interval, MaxBatch and Flush are the meaningful knobs; the rest have sane defaults.

type Job

type Job struct {
	// Name labels the job in log records (`name=…`). Required for
	// readable logs when a service registers more than one ticker.
	Name string

	// Interval is the happy-path cadence. Every successful Run
	// schedules the next wakeup `Interval ± Jitter` from now.
	Interval time.Duration

	// RetryInterval is the cadence used after Run returns a non-nil
	// error. Zero falls back to Interval. Use a value smaller than
	// Interval (e.g. 1h vs 24h) so a recovery happens quickly
	// without spamming the upstream during a sustained outage.
	RetryInterval time.Duration

	// Jitter is the maximum +/- variation applied to every wakeup.
	// Zero disables jitter (predictable but synchronizes replicas).
	// 30m on a 24h interval is plenty for cross-pod desynchronisation.
	Jitter time.Duration

	// RunOnStart fires Run once immediately when the goroutine
	// starts, before the first Interval-long sleep. Use when "fresh
	// data right away" matters (cache priming) and skip when the
	// upstream is expensive enough that a startup-storm hurts.
	RunOnStart bool

	// Fn is the job body. Returning a non-nil error switches the
	// next schedule to RetryInterval. A panic terminates the
	// goroutine — wrap with defer/recover if survival matters.
	Fn func(ctx context.Context) error

	// Logger records start / OK / error events. nil = log.Default.
	Logger logger
}

Job describes one recurring task. The zero value is incomplete (no Run = nothing to do); set Name + Interval + Run at minimum.

Jump to

Keyboard shortcuts

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