forked from Azure/azure-service-bus-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
scheduled_message_examples_test.go
84 lines (71 loc) · 2.22 KB
/
scheduled_message_examples_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
package servicebus_test
import (
"context"
"fmt"
"os"
"time"
"github.com/Azure/azure-service-bus-go"
)
func Example_scheduledMessage() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING")
if connStr == "" {
fmt.Println("FATAL: expected environment variable SERVICEBUS_CONNECTION_STRING not set")
return
}
// Create a client to communicate with a Service Bus Namespace.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println("FATAL: ", err)
return
}
// Create a client to communicate with the queue. (The queue must have already been created, see `QueueManager`)
client, err := ns.NewQueue("scheduledmessages")
if err != nil {
fmt.Println("FATAL: ", err)
return
}
// purge all of the existing messages in the queue
purgeMessages(ns)
// The delay that we should schedule a message for.
const waitTime = 1 * time.Minute
// Service Bus guarantees roughly a one minute window. So that our tests aren't flaky, we'll buffer our expectations
// on either side.
const buffer = 20 * time.Second
expectedTime := time.Now().Add(waitTime)
msg := servicebus.NewMessageFromString("to the future!!")
msg.ScheduleAt(expectedTime)
err = client.Send(ctx, msg)
if err != nil {
fmt.Println("FATAL: ", err)
return
}
err = client.ReceiveOne(
ctx,
servicebus.HandlerFunc(func(ctx context.Context, msg *servicebus.Message) error {
received := time.Now()
if received.Before(expectedTime.Add(buffer)) && received.After(expectedTime.Add(-buffer)) {
fmt.Println("Received when expected!")
} else {
fmt.Println("Received outside the expected window.")
}
return msg.Complete(ctx)
}))
if err != nil {
fmt.Println("FATAL: ", err)
return
}
// Output: Received when expected!
}
func purgeMessages(ns *servicebus.Namespace) {
purgeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, _ := ns.NewQueue("scheduledmessages")
defer func() {
_ = client.Close(purgeCtx)
}()
defer cancel()
_ = client.Receive(purgeCtx, servicebus.HandlerFunc(func(ctx context.Context, msg *servicebus.Message) error {
return msg.Complete(ctx)
}))
}