Normally, jobs involve a JobArgs
and worker pair. Workers that need only trivial implementations can use WorkFunc
to define workers that run functions to work.
Functions as workers
Defining a job normally involves a pair of structs — a JobArgs
implementation containing job arguments, and a worker struct providing a Work
definition. When prototyping, or where a job is involved that requires only a trivial definition, the worker struct can be omitted by wrapping a function with WorkFunc
:
type WorkFuncArgs struct {
Message string `json:"message"`
}
func (WorkFuncArgs) Kind() string { return "work_func" }
...
workers := river.NewWorkers()
river.AddWorker(workers, river.WorkFunc(func(ctx context.Context, j *river.Job[WorkFuncArgs]) error {
fmt.Printf("Message: %s", j.Args.Message)
return nil
}))
See the WorkFunc
example for complete code.
Worker structs are generally preferable for better organization and testability, but WorkFunc
can be handy as a more concise alternative depending on the situation.