-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlifetime_test.go
87 lines (75 loc) · 1.71 KB
/
lifetime_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
package lifetime_test
import (
"context"
"fmt"
"github.com/tomwright/lifetime"
"sync"
"time"
)
type testService struct {
name string
stop bool
stopMu sync.RWMutex
startupDuration time.Duration
shutdownDuration time.Duration
}
func (s *testService) Start() error {
time.Sleep(s.startupDuration)
fmt.Printf("%s: Started\n", s.name)
for {
s.stopMu.RLock()
if s.stop {
s.stopMu.RUnlock()
break
}
s.stopMu.RUnlock()
time.Sleep(time.Millisecond * 10)
}
return nil
}
func (s *testService) Stop() {
s.stopMu.Lock()
defer s.stopMu.Unlock()
time.Sleep(s.shutdownDuration)
fmt.Printf("%s: Stopped\n", s.name)
s.stop = true
}
// ExampleLifetime shows a basic example of how you can use Lifetime.
func ExampleLifetime() {
// Create a lifetime and initialises it.
lt := lifetime.New(context.Background()).
Init()
fmt.Printf("Starting services\n")
// Service A takes 100ms to start up and 800ms to shutdown.
serviceA := &testService{
name: "a",
startupDuration: time.Millisecond * 100,
shutdownDuration: time.Millisecond * 800,
}
// Service B takes 800ms to start up and 100ms to shutdown.
serviceB := &testService{
name: "b",
startupDuration: time.Millisecond * 800,
shutdownDuration: time.Millisecond * 100,
}
// Start both services.
lt.Start(serviceA)
lt.Start(serviceB)
// Wait some time and trigger an application shutdown.
go func() {
<-time.After(time.Millisecond * 1500)
fmt.Printf("Shutting down\n")
lt.Shutdown()
}()
// Wait for all services to stop.
lt.Wait()
fmt.Printf("Shutdown\n")
// Output:
// Starting services
// a: Started
// b: Started
// Shutting down
// b: Stopped
// a: Stopped
// Shutdown
}