batcher

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 4 Imported by: 0 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 batcher groups items added one at a time into batches for a flush function.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("batcher: closed")

ErrClosed is returned by Add after Close.

Functions

This section is empty.

Types

type Batcher

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

Batcher collects items and hands them to flush in batches of at most MaxItems, at the latest MaxWait after the first item of the batch. Each flush runs on its own goroutine, never with the batcher's lock held.

func New

func New[T any](cfg Config, flush func(context.Context, []T)) (*Batcher[T], error)

New returns a running batcher that calls flush with each batch. The context passed to flush is canceled when Close is called; Close still flushes the pending items, so flush decides whether to finish the work or fail it.

func (*Batcher[T]) Add

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

Add queues item. When item fills a batch, Add starts its flush, first waiting for a free slot if MaxInFlight flushes are running. If ctx ends while waiting, Add returns nil and the item stays queued for the timer.

func (*Batcher[T]) Close

func (b *Batcher[T]) Close()

Close stops accepting items, cancels the flush context, flushes the pending items and waits for every flush to return. Idempotent.

type Config

type Config struct {
	// MaxItems flushes a batch when it holds this many items, and caps the
	// size of every batch. 0 flushes on MaxWait only.
	MaxItems int
	// MaxWait flushes a batch this long after its first item was added. Items
	// left over after a batch was taken wait MaxWait again from then.
	MaxWait time.Duration
	// MaxInFlight caps concurrent flushes. When the cap is reached, Add of an
	// item that fills a batch blocks until a flush finishes. 0 means no cap.
	MaxInFlight int
}

Config sets when a batch is flushed and how many flushes run at once.

Jump to

Keyboard shortcuts

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