Documentation
¶
Overview ¶
Package task provides wrappers for simplified management of async functions.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrAlreadyStarted = errors.New("task already started")
ErrAlreadyStarted is returned by any task's Run method if called more than once.
var ErrCleanupFailed = errors.New("one or more cleanup functions failed")
ErrCleanupFailed is used as the base error when cleanup functions return errors but no task error occurred.
var ErrCleanupTimeout = errors.New("cleanup timed out")
ErrCleanupTimeout is returned by Wait when cleanup functions do not complete within the cleanup timeout. If tasks also failed, the task error is provided as the base and cleanup errors are attached; see CleanupErrors.
var ErrManagerStopped = errors.New("manager already stopped")
ErrManagerStopped is returned when Run or RunEphemeral is called after the manager has stopped.
var ErrShutdownTimeout = errors.New("shutdown timed out waiting for tasks to stop")
ErrShutdownTimeout is returned by Wait when tasks do not stop within the shutdown timeout.
Functions ¶
This section is empty.
Types ¶
type Action ¶
Action is a function that performs a unit of work. It must return nil when the context is cancelled.
type CleanupErrors ¶
type CleanupErrors []error
CleanupErrors holds errors returned by registered cleanup functions. Retrieve it from a Wait error using xerrors.ExtractCleanupErrors.
func (CleanupErrors) LogValue ¶
func (e CleanupErrors) LogValue() slog.Value
LogValue implements slog.LogValuer.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard prevents a task's Run method from being called more than once. Embed it in a Task struct and call TryStart at the top of Run.
Example ¶
ExampleGuard demonstrates the Guard's double-run prevention.
package main
import (
"errors"
"fmt"
"github.com/wood-jp/task"
)
func main() {
var g task.Guard
fmt.Println(g.TryStart() == nil)
fmt.Println(errors.Is(g.TryStart(), task.ErrAlreadyStarted))
}
Output: true true
func (*Guard) TryStart ¶
TryStart returns nil on the first call and a wrapped ErrAlreadyStarted on all subsequent calls.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages a group of tasks that should all stop when any one of them stops.
Example ¶
ExampleManager demonstrates creating a Manager, running a task, and stopping cleanly.
package main
import (
"context"
"log"
"github.com/wood-jp/task"
)
// contextTask is a Task that blocks until its context is cancelled.
type contextTask struct{ name string }
func (t *contextTask) Name() string { return t.name }
func (t *contextTask) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
func main() {
m := task.NewManager()
if err := m.Run(&contextTask{name: "worker"}); err != nil {
log.Fatal(err)
}
// Stop cancels all tasks and waits for them to finish.
if err := m.Stop(); err != nil {
log.Fatal(err)
}
}
Output:
func (*Manager) Cleanup ¶
Cleanup registers a function that runs after all tasks are stopped. Similar to defer, cleanup functions are executed in the reverse order in which they were registered. Any errors returned are collected and attached to the Wait return value as CleanupErrors.
Example ¶
ExampleManager_Cleanup demonstrates registering a cleanup function that runs after all tasks have stopped.
package main
import (
"context"
"fmt"
"log"
"github.com/wood-jp/task"
)
// contextTask is a Task that blocks until its context is cancelled.
type contextTask struct{ name string }
func (t *contextTask) Name() string { return t.name }
func (t *contextTask) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
func main() {
m := task.NewManager()
m.Cleanup(func() error {
fmt.Println("cleanup: closing database")
return nil
})
if err := m.Run(&contextTask{name: "worker"}); err != nil {
log.Fatal(err)
}
_ = m.Stop()
}
Output: cleanup: closing database
func (*Manager) Run ¶
Run immediately starts all of the given tasks. Returns ErrManagerStopped if the manager has already stopped.
func (*Manager) RunEphemeral ¶
RunEphemeral immediately starts all of the given tasks. These tasks are expected to terminate without error while others continue running. Returns ErrManagerStopped if the manager has already stopped.
func (*Manager) Stop ¶
Stop cancels the context immediately and waits for all running tasks to complete.
func (*Manager) Wait ¶
Wait blocks until all tasks are complete, then executes all registered cleanup functions. It returns the first encountered task error, with any cleanup errors attached as CleanupErrors (retrieve via xerrors.Extract). If tasks do not stop within the shutdown timeout, Wait returns ErrShutdownTimeout. If cleanup functions do not complete within the cleanup timeout, Wait returns ErrCleanupTimeout. Concurrent or repeated calls all return the same result.
type Option ¶
type Option func(options *options)
Option is an option func for NewManager.
func WithCleanupTimeout ¶
WithCleanupTimeout sets the maximum total duration for all cleanup functions to complete. Defaults to 10 seconds.
func WithContext ¶
WithContext sets a parent context for the manager. When the parent context is cancelled, the manager will begin shutting down.
func WithLogger ¶
WithLogger sets the logger to be used.
func WithShutdownTimeout ¶
WithShutdownTimeout sets the maximum duration to wait for tasks to stop after the manager context is cancelled. Defaults to 30 seconds.
type Task ¶
type Task interface {
// Run must execute the work of this service and block until the context
// is cancelled, or until the service is unable to continue due to an error.
// Run must return nil when the context is cancelled; a non-nil error signals
// a failure and will cause the manager to cancel all other tasks. In
// particular, do not return ctx.Err(): context.Canceled is a non-nil error
// and will be treated as a failure.
Run(context.Context) error
// Name provides a human-friendly name for use in logging.
Name() string
}
Task represents a background service.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
graceful-shutdown
command
Package main demonstrates graceful shutdown using the task package.
|
Package main demonstrates graceful shutdown using the task package. |
|
Package loop provides a Task that repeatedly executes an action function.
|
Package loop provides a Task that repeatedly executes an action function. |
|
Package ossignal provides a Task that listens for signals from the operating system.
|
Package ossignal provides a Task that listens for signals from the operating system. |
|
Package poll provides a Task that periodically executes an action function.
|
Package poll provides a Task that periodically executes an action function. |
|
Package sigtrigger provides a Task that executes an action each time a configured OS signal is received.
|
Package sigtrigger provides a Task that executes an action each time a configured OS signal is received. |