Skip to content

Commit 4d141b3

Browse files
authored
Add example for a job scheduled in the future (riverqueue#70)
It came up on a GitHub thread that someone was confused about how to schedule a job to be worked in the future. You can figure this out from the godoc, but it doesn't hurt to add an explicit example for how to schedule a job for the future.
1 parent 42cf318 commit 4d141b3

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

example_scheduled_job_test.go

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

0 commit comments

Comments
 (0)