-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
74 lines (59 loc) · 1.36 KB
/
example_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
package stop_test
import (
"fmt"
"time"
"github.com/upsight/stop"
)
func ExampleChannelStopper() {
s := stop.NewChannelStopper()
go func() {
<-s.StopChannel()
fmt.Println("Stopper is stopping")
s.Stopped()
}()
s.Stop()
s.WaitForStopped()
fmt.Println("Stopper has stopped")
// Output:
// Stopper is stopping
// Stopper has stopped
}
func ExampleGroup() {
type Service struct {
*stop.ChannelStopper
t *time.Timer
}
runService := func(s *Service, sg *stop.Group, n int) {
defer s.Stopped()
select {
case <-s.StopChannel():
fmt.Println("Service", n, "stopping")
case <-s.t.C:
fmt.Println("Service", n, "timer expired")
sg.Stop()
}
}
// Add two services to a stop group. The timer for the first
// service will finish first. It will stop the group, which will
// cause the stop for the other service to be called.
sg := stop.NewGroup()
s1 := &Service{
ChannelStopper: stop.NewChannelStopper(),
t: time.NewTimer(1 * time.Second),
}
sg.Add(s1)
go runService(s1, sg, 1)
s2 := &Service{
ChannelStopper: stop.NewChannelStopper(),
t: time.NewTimer(2 * time.Second),
}
sg.Add(s2)
go runService(s2, sg, 2)
// Wait for all the services to finish stopping.
sg.Wait()
fmt.Println("Services have stopped")
// Output:
// Service 1 timer expired
// Service 2 stopping
// Services have stopped
}