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

Function Example_jobCancelFromClient

example_job_cancel_from_client_test.go:41–101  ·  view source on GitHub ↗

Example_jobCancelFromClient demonstrates how to permanently cancel a job from any Client using JobCancel.

()

Source from the content-addressed store, hash-verified

39// Example_jobCancelFromClient demonstrates how to permanently cancel a job from
40// any Client using JobCancel.
41func Example_jobCancelFromClient() {
42 ctx := context.Background()
43
44 dbPool, err := pgxpool.New(ctx, riversharedtest.TestDatabaseURL())
45 if err != nil {
46 panic(err)
47 }
48 defer dbPool.Close()
49
50 jobChan := make(chan int64)
51
52 workers := river.NewWorkers()
53 river.AddWorker(workers, &SleepingWorker{jobChan: jobChan})
54
55 riverClient, err := river.NewClient(riverpgxv5.New(dbPool), initTestConfig(ctx, dbPool, &river.Config{
56 Logger: slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelWarn, ReplaceAttr: slogutil.NoLevelTimeJobID})),
57 Queues: map[string]river.QueueConfig{
58 river.QueueDefault: {MaxWorkers: 10},
59 },
60 Workers: workers,
61 }))
62 if err != nil {
63 panic(err)
64 }
65
66 // Not strictly needed, but used to help this test wait until job is worked.
67 subscribeChan, subscribeCancel := riverClient.Subscribe(river.EventKindJobCancelled)
68 defer subscribeCancel()
69
70 if err := riverClient.Start(ctx); err != nil {
71 panic(err)
72 }
73 insertRes, err := riverClient.Insert(ctx, CancellingArgs{ShouldCancel: true}, nil)
74 if err != nil {
75 panic(err)
76 }
77 select {
78 case <-jobChan:
79 case <-time.After(2 * time.Second):
80 panic("no jobChan signal received")
81 }
82
83 // There is presently no way to wait for the client to be 100% ready, so we
84 // sleep for a bit to give it time to start up. This is only needed in this
85 // example because we need the notifier to be ready for it to receive the
86 // cancellation signal.
87 time.Sleep(500 * time.Millisecond)
88
89 if _, err = riverClient.JobCancel(ctx, insertRes.Job.ID); err != nil {
90 panic(err)
91 }
92 // Wait for jobs to complete. Only needed for purposes of the example test.
93 riversharedtest.WaitOrTimeoutN(testutil.PanicTB(), subscribeChan, 1)
94
95 if err := riverClient.Stop(ctx); err != nil {
96 panic(err)
97 }
98

Callers

nothing calls this directly

Calls 15

TestDatabaseURLFunction · 0.92
NewWorkersFunction · 0.92
AddWorkerFunction · 0.92
NewClientFunction · 0.92
NewFunction · 0.92
WaitOrTimeoutNFunction · 0.92
PanicTBFunction · 0.92
SubscribeMethod · 0.80
InsertMethod · 0.80
AfterMethod · 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…