task

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 10 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 task runs functions concurrently, with a time limit, or in separate goroutines while keeping the application's scope in each piece of work:

users := task.Go(r, db.Table("users").Count)
orders := task.Go(r, db.Table("orders").Count)

userCount, err := users.Wait()
// ...
orderCount, err := orders.Wait()

Use Run to run functions concurrently and wait for all of them, Both to run two value-returning functions concurrently, NewGroup to collect a dynamic set of concurrent functions, Map and Each to process a slice with a concurrency limit, First to race competing functions, Timeout to bound how long a function may run, Sleep to pause with context cancellation, and Go to start background work you collect later with Task.Wait.

Each function receives a context that preserves the caller's values, such as the application, the authenticated user, and the active trace, so the database, cache, and HTTP client work as they do in the caller. A panic in a function is recovered and returned as a *web.PanicError, which produces a 500 response instead of crashing the process.

Inside a database transaction, such as in db.Transaction or a test using laraveltest.RefreshDatabase, functions still run concurrently and their queries share the transaction's connection in turn.

For fire-and-forget work that no caller waits for, use web.Request.Background or laravel.Background, which the server waits for during shutdown.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Both

func Both[A, B any](ctx context.Context, fnA func(ctx context.Context) (A, error), fnB func(ctx context.Context) (B, error)) (A, B, error)

Both executes fnA and fnB concurrently and returns both values once both finish. If either function fails or panics, Both cancels the other's context with that error as the cause, waits for both to return, and returns the zero values with the first error:

user, orders, err := task.Both(r,
	func(ctx context.Context) (models.User, error) { return model.Find[models.User](ctx, id) },
	func(ctx context.Context) ([]models.Order, error) {
		return model.Query[models.Order]().WhereEq("user_id", id).Get(ctx)
	},
)

func Each

func Each[T any](ctx context.Context, items []T, limit int, fn func(ctx context.Context, item T) error) error

Each calls fn for each element of items with at most limit calls running at once, stopping at the first error as Map does. Use it for bounded concurrent work that produces no result slice:

err := task.Each(r, emails, 5, func(ctx context.Context, email string) error {
	return mail.Send(ctx, email, welcome)
})

Each panics if limit is less than 1.

func First

func First[T any](ctx context.Context, fns ...func(ctx context.Context) (T, error)) (T, error)

First runs the given functions concurrently and returns the result of whichever finishes first, such as racing a primary and backup service:

rates, err := task.First(r, primary.LatestRates, backup.LatestRates)

The first function to return wins, even if it returns an error. Once one function finishes, First cancels the context of the others and returns immediately without waiting for them, discarding their results. Pass functions that stop promptly when their context is canceled, such as database queries and HTTP requests. First panics if no functions are provided.

func Map

func Map[T, R any](ctx context.Context, items []T, limit int, fn func(ctx context.Context, item T) (R, error)) ([]R, error)

Map calls fn for each element of items with at most limit calls running at once, and returns the results in the same order as items. Use it to fan out work, such as fetching pages from an API, without flooding the upstream service:

responses, err := task.Map(r, orgs, 5, func(ctx context.Context, org string) (*httpclient.Response, error) {
	return httpclient.URLParameters("org", org).Get(ctx, "https://api.github.com/orgs/{org}")
})

When a call returns an error, Map stops starting new calls, cancels the context of calls still in flight, waits for them to finish, and returns that first error. Map panics if limit is less than 1.

func Run

func Run(ctx context.Context, fns ...func(ctx context.Context) error) error

Run executes the given functions concurrently, waits for all of them to finish, and returns the first non-nil error:

var user models.User
var orders []models.Order
err := task.Run(r,
	func(ctx context.Context) (err error) {
		user, err = model.Find[models.User](ctx, id)
		return err
	},
	func(ctx context.Context) (err error) {
		orders, err = model.Query[models.Order]().Where("user_id", "=", id).Get(ctx)
		return err
	},
)

When one function fails, Run cancels the context passed to the remaining functions with that error as the cause so they can stop early. Each function writes to its own variables, and Run returns only after every function has returned, so the caller can read those results safely once Run completes.

func Sleep

func Sleep(ctx context.Context, d time.Duration) error

Sleep pauses for d, such as between calls to a rate-limited API, and returns nil. If ctx is canceled before d elapses, Sleep returns immediately with an error that matches both the context's error and its cause with errors.Is:

if err := task.Sleep(ctx, 500*time.Millisecond); err != nil {
	return err
}

func Timeout

func Timeout[T any](ctx context.Context, limit time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

Timeout runs fn with a context that expires after limit and returns fn's result, or a *TimeoutError if the limit expires first:

res, err := task.Timeout(r, 3*time.Second, func(ctx context.Context) (*httpclient.Response, error) {
	return httpclient.Get(ctx, "https://rates.example.com/latest")
})
if _, ok := errors.AsType[*task.TimeoutError](err); ok {
	// Fall back to the rates from the cache...
}

A handler that fails with a *TimeoutError responds with 504 Gateway Timeout. When the limit expires, Timeout cancels fn's context and returns immediately without waiting for fn to finish, discarding its result.

Types

type Group

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

Group runs a dynamic set of functions concurrently with shared cancellation on the first error, preserving the application scope and recovering panics as *web.PanicError. Create a Group with NewGroup, add functions with Group.Go, and wait for them with Group.Wait:

g := task.NewGroup(r)
g.Go(func(ctx context.Context) error { return syncContacts(ctx) })
if includeBilling {
	g.Go(func(ctx context.Context) error { return syncInvoices(ctx) })
}
if err := g.Wait(); err != nil {
	return web.Fail(err)
}

func NewGroup

func NewGroup(ctx context.Context) *Group

NewGroup creates a *Group derived from ctx. Always call Group.Wait to release resources and wait for every started function to finish.

func (*Group) Go

func (g *Group) Go(fn func(ctx context.Context) error)

Go starts fn in a new goroutine belonging to g. The function receives the group's context, which is canceled when any function in g returns an error or panics.

func (*Group) Wait

func (g *Group) Wait() error

Wait blocks until every function started with Group.Go returns, releases the group's context, and returns the first non-nil error, if any.

type Task

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

Task represents a function running in a goroutine started by Go. Call Task.Wait to wait for it and collect its result.

func Go

func Go[T any](ctx context.Context, fn func(ctx context.Context) (T, error)) *Task[T]

Go starts fn in a separate goroutine and returns immediately so the caller can do other work and collect the result later with Task.Wait:

orders := task.Go(r, db.Table("orders").Count)

users, err := db.Table("users").Count(r)
if err != nil {
	return web.Fail(err)
}
count, err := orders.Wait()

The function receives a context that preserves ctx's values and cancellation, so it stops when the request ends. Errors are not reported automatically, so check the error returned by Task.Wait. A task that no caller waits for keeps running, and the server does not wait for it during shutdown. For shutdown-tracked background work, use web.Request.Background instead.

func (*Task[T]) Wait

func (t *Task[T]) Wait() (T, error)

Wait blocks until the task's function finishes and returns its value and error. A panic in the function is returned as a *web.PanicError. Wait is safe to call more than once and from multiple goroutines.

type TimeoutError

type TimeoutError struct {
	// Limit is the duration allowed for the work.
	Limit time.Duration
}

TimeoutError reports that work started by Timeout did not finish within its time limit. Returning it from a handler produces a 504 Gateway Timeout response, and it matches context.DeadlineExceeded with errors.Is.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error returns a message describing the exceeded time limit.

func (*TimeoutError) StatusCode

func (e *TimeoutError) StatusCode() int

StatusCode returns 504 Gateway Timeout.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout reports true, implementing the net.Error timeout interface.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns context.DeadlineExceeded.

Jump to

Keyboard shortcuts

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