-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_util.go
92 lines (77 loc) · 1.48 KB
/
module_util.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
package util
import (
"os"
"os/signal"
"sync"
"syscall"
)
// 模块化
type Module interface {
Init() error
Run()
Stop()
}
//@
type DefaultModule struct {
}
func (this DefaultModule) Init() error {
return nil
}
func (this DefaultModule) Run() {
}
func (this DefaultModule) Stop() {
}
// DefaultModuleManager default module manager
type DefaultModuleManager struct {
Module
Modules []Module
}
//
func NewDefaultModuleManager() *DefaultModuleManager {
return &DefaultModuleManager{
Modules: make([]Module, 0, 5),
}
}
// 初始化所有模块
func (this *DefaultModuleManager) Init() error {
for i := 0; i < len(this.Modules); i++ {
err := this.Modules[i].Init()
if err != nil {
return err
}
}
return nil
}
// 运行模块
func (this *DefaultModuleManager) Run() {
for i := 0; i < len(this.Modules); i++ {
this.Modules[i].Run()
}
}
func (this *DefaultModuleManager) Stop() {
var wg sync.WaitGroup
for i := 0; i < len(this.Modules); i++ {
wg.Add(1)
go func(module Module) {
module.Stop()
wg.Done()
}(this.Modules[i])
}
wg.Wait()
}
// 添加模块
func (this *DefaultModuleManager) AppendModule(module Module) Module {
this.Modules = append(this.Modules, module)
return module
}
// WaitTerminateSignal wait signal to end the program
func WaitForTerminate() {
exitChan := make(chan struct{})
signalChan := make(chan os.Signal, 1)
go func() {
<-signalChan
close(exitChan)
}()
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
<-exitChan
}