Abstract background worker process
The github.com/go-nacelle/workerbase
package provides an abstract background worker process.
A worker is a process that periodically polls an external resource in order to discover or perform its main unit of work. A base worker is an abstract process whose behavior can be be configured by implementing the WorkerSpec
interface.
A worker process is created by supplying a specification, described below, that controls its behavior.
|
|
A worker specification is a struct with an Init
and a Tick
method. Both methods take a context as a parameter. On process shutdown, this context object is cancelled so that any long-running work in the tick method can be cleanly abandoned. Each method may return an error value, which signals a fatal error to the process that runs it.
The following example uses a database connection injected by the service container, and pings it to logs its latency. The worker process will call the tick method in a loop based on its interval configuration while the process remains active.
|
|
If the worker specification also implements the Finalize
method, it will be called after the last invocation of the tick method (regardless of its return value).
|
|
This library comes with an example project. You can see an additional example of a worker process in the example repository, specifically the worker spec definition.