-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.go
122 lines (94 loc) · 1.91 KB
/
application.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package application
import (
"context"
"os"
"os/signal"
"runtime"
"sync"
)
// waitGroupContextKey contextKey for wait group
const waitGroupContextKey = contextKey("APP:WAIT_GROUP")
// IApplication interface
type IApplication interface {
// Background run the application in background, and wait for OS signal to terminate
Background()
// Run a runnable in a goroutine
Start(runnable Runnable)
// Stop the application
Stop()
// Run and wait all runnable stopped
Wait()
}
// WaitGroupFromContext get a sync.WaitGroup from context, if available
func WaitGroupFromContext(ctx context.Context) *sync.WaitGroup {
value := ctx.Value(waitGroupContextKey)
if value == nil {
return nil
}
switch wg := value.(type) {
case *sync.WaitGroup:
return wg
default:
return nil
}
}
type application struct {
wg *sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
}
// NewApplication create a new application that can run in background
func NewApplication(ctx context.Context) IApplication {
app := &application{
wg: &sync.WaitGroup{},
}
if ctx == nil {
ctx = context.Background()
}
app.ctx, app.cancel = context.WithCancel(
context.WithValue(ctx, waitGroupContextKey, app.wg),
)
return app
}
func (a *application) Start(runnable Runnable) {
a.wg.Add(1)
go func() {
defer a.wg.Done()
runnable(a.ctx)
}()
}
func (a *application) Stop() {
a.cancel()
}
func (a *application) Wait() {
defer runtime.GC()
done := make(chan bool, 1)
go func() {
a.wg.Wait()
done <- true
}()
select {
case <-done:
break
case <-a.ctx.Done():
break
}
}
func (a *application) Background() {
// force GC so that everything is cleared
defer runtime.GC()
a.wg.Add(1)
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt, os.Kill)
go func() {
defer a.wg.Done()
select {
case <-signalCh:
a.cancel()
return
case <-a.ctx.Done():
return
}
}()
a.wg.Wait()
}