worker

package
v0.0.0-...-3f3c78e Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWorkerClosed  = errors.New("worker is closed")
	ErrWorkerTooBusy = errors.New("worker is already overloaded")
)

Errors that may occur when sending tasks to a worker.

Functions

This section is empty.

Types

type Config

type Config[T any] struct {
	// The size of the bounded channel.
	ChannelSize int
	// Timeout after which `OnTimeout` is called.
	Timeout time.Duration
	// A closure that is called once `Timeout` is reached.
	OnTimeout func()
	// A closure that is executed upon reception of a task.
	OnTask func(T)
}

Configuration for the worker.

type Worker

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

We need to wrap the channel in a struct so that we can close it from the outside and check by the sender if the channel is closed (there is no elegant way to do it in Go).

func StartWorker

func StartWorker[T any](c Config[T]) *Worker[T]

Starts a worker that periodically (specified by the configuration) executes a `c.OnTimeout` closure if no tasks have been received on a channel for a `c.Timeout`. The worker will stop once the channel is closed, i.e. once the user calls `Stop` explicitly.

func (*Worker[T]) Send

func (c *Worker[T]) Send(task T) error

Send a task to the worker. Returns `true` if the task has been sent, `false` if the channel is already closed.

func (*Worker[T]) Stop

func (c *Worker[T]) Stop()

Stop the channel unless already closed.

Jump to

Keyboard shortcuts

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