-
Notifications
You must be signed in to change notification settings - Fork 93
/
example_scheduled_job_test.go
88 lines (71 loc) · 2.13 KB
/
example_scheduled_job_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package river_test
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/riverqueue/river"
"github.com/riverqueue/river/internal/riverinternaltest"
"github.com/riverqueue/river/riverdriver/riverpgxv5"
"github.com/riverqueue/river/rivershared/util/slogutil"
)
type ScheduledArgs struct {
Message string `json:"message"`
}
func (ScheduledArgs) Kind() string { return "scheduled" }
type ScheduledWorker struct {
river.WorkerDefaults[ScheduledArgs]
}
func (w *ScheduledWorker) Work(ctx context.Context, job *river.Job[ScheduledArgs]) error {
fmt.Printf("Message: %s\n", job.Args.Message)
return nil
}
// Example_scheduledJob demonstrates how to schedule a job to be worked in the
// future.
func Example_scheduledJob() {
ctx := context.Background()
dbPool, err := pgxpool.NewWithConfig(ctx, riverinternaltest.DatabaseConfig("river_test_example"))
if err != nil {
panic(err)
}
defer dbPool.Close()
// Required for the purpose of this test, but not necessary in real usage.
if err := riverinternaltest.TruncateRiverTables(ctx, dbPool); err != nil {
panic(err)
}
workers := river.NewWorkers()
river.AddWorker(workers, &ScheduledWorker{})
riverClient, err := river.NewClient(riverpgxv5.New(dbPool), &river.Config{
Logger: slog.New(&slogutil.SlogMessageOnlyHandler{Level: slog.LevelWarn}),
Queues: map[string]river.QueueConfig{
river.QueueDefault: {MaxWorkers: 100},
},
TestOnly: true, // suitable only for use in tests; remove for live environments
Workers: workers,
})
if err != nil {
panic(err)
}
if err := riverClient.Start(ctx); err != nil {
panic(err)
}
_, err = riverClient.Insert(ctx,
ScheduledArgs{
Message: "hello from the future",
},
&river.InsertOpts{
// Schedule the job to be worked in three hours.
ScheduledAt: time.Now().Add(3 * time.Hour),
})
if err != nil {
panic(err)
}
// Unlike most other examples, we don't wait for the job to be worked since
// doing so would require making the job's scheduled time contrived, and the
// example therefore less realistic/useful.
if err := riverClient.Stop(ctx); err != nil {
panic(err)
}
// Output:
}