MCPcopy
hub / github.com/riverqueue/river / Example_workFunc

Function Example_workFunc

example_work_func_test.go:24–73  ·  view source on GitHub ↗

Example_workFunc demonstrates the use of river.WorkFunc, which can be used to easily add a worker with only a function instead of having to implement a full worker struct.

()

Source from the content-addressed store, hash-verified

22// easily add a worker with only a function instead of having to implement a
23// full worker struct.
24func Example_workFunc() {
25 ctx := context.Background()
26
27 dbPool, err := pgxpool.New(ctx, riversharedtest.TestDatabaseURL())
28 if err != nil {
29 panic(err)
30 }
31 defer dbPool.Close()
32
33 workers := river.NewWorkers()
34 river.AddWorker(workers, river.WorkFunc(func(ctx context.Context, job *river.Job[WorkFuncArgs]) error {
35 fmt.Printf("Message: %s", job.Args.Message)
36 return nil
37 }))
38
39 riverClient, err := river.NewClient(riverpgxv5.New(dbPool), initTestConfig(ctx, dbPool, &river.Config{
40 Queues: map[string]river.QueueConfig{
41 river.QueueDefault: {MaxWorkers: 100},
42 },
43 Workers: workers,
44 }))
45 if err != nil {
46 panic(err)
47 }
48
49 // Out of example scope, but used to wait until a job is worked.
50 subscribeChan, subscribeCancel := riverClient.Subscribe(river.EventKindJobCompleted)
51 defer subscribeCancel()
52
53 if err := riverClient.Start(ctx); err != nil {
54 panic(err)
55 }
56
57 _, err = riverClient.Insert(ctx, WorkFuncArgs{
58 Message: "hello from a function!",
59 }, nil)
60 if err != nil {
61 panic(err)
62 }
63
64 // Wait for jobs to complete. Only needed for purposes of the example test.
65 riversharedtest.WaitOrTimeoutN(testutil.PanicTB(), subscribeChan, 1)
66
67 if err := riverClient.Stop(ctx); err != nil {
68 panic(err)
69 }
70
71 // Output:
72 // Message: hello from a function!
73}

Callers

nothing calls this directly

Calls 14

TestDatabaseURLFunction · 0.92
NewWorkersFunction · 0.92
AddWorkerFunction · 0.92
WorkFuncFunction · 0.92
NewClientFunction · 0.92
NewFunction · 0.92
WaitOrTimeoutNFunction · 0.92
PanicTBFunction · 0.92
SubscribeMethod · 0.80
InsertMethod · 0.80
initTestConfigFunction · 0.70
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…