Documentation
¶
Overview ¶
Package taskmanager provides a basic way to start multiple long-running Goroutines.
Example ¶
package main import ( "context" "github.com/clambin/go-common/taskmanager" "github.com/clambin/go-common/taskmanager/httpserver" "github.com/clambin/go-common/taskmanager/prometheus" "net/http" "os" "os/signal" ) func main() { m := taskmanager.New() // Add a Goroutine. We use TaskFunc to convert a func to a Task // without having to declare a struct that adheres to the Task interface. _ = m.Add(taskmanager.TaskFunc(func(ctx context.Context) error { <-ctx.Done() return ctx.Err() })) // Add an HTTP Server. r := http.NewServeMux() r.HandleFunc("/test", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("hello")) }) _ = m.Add(httpserver.New(":8080", r)) // Add a Prometheus server _ = m.Add(prometheus.New(prometheus.WithAddr(":9092"))) // Run until the program is interrupted. ctx, done := signal.NotifyContext(context.Background(), os.Interrupt) defer done() // Start the task manager. This will run until the context is marked as done. if err := m.Run(ctx); err != nil { panic(err) } }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrAlreadyRunning = errors.New("task manager already running")
ErrAlreadyRunning indicates the Manager is already running and the requested function cannot be performed.
Functions ¶
This section is empty.
Types ¶
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager groups a number of Task instances
func (*Manager) Add ¶
Add adds a Task to the Manager. This can only be done when the Manager is not running. Otherwise, it returns ErrAlreadyRunning.
func (*Manager) Run ¶
Run starts the different Task objects as separate Goroutines and waits for the context to be marked as Done. It then stops all Tasks and returns any returned errors.
If any Task returns an error before the context is marked as Done, Run will stop all Goroutines and return the error of the failing Task.
Only one instance of a Manager can run at a single time. If Run is called while the Manager is already running, Run returns ErrAlreadyRunning.
type Task ¶
Task is the interface that any taskmanager task must adhere to. It consists of a single Run method. The task should run until the provided context is marked as Done, or a fatal error occurs.
Directories
¶
Path | Synopsis |
---|---|
Package httpserver implements a Task that runs an HTTP server.
|
Package httpserver implements a Task that runs an HTTP server. |
Package prometheus provides a Task that runs an HTTP server for the Prometheus default registry.
|
Package prometheus provides a Task that runs an HTTP server for the Prometheus default registry. |