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.
()
| 22 | // easily add a worker with only a function instead of having to implement a |
| 23 | // full worker struct. |
| 24 | func 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 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…