-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposite_wait_listener.go
74 lines (62 loc) · 1.62 KB
/
composite_wait_listener.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 listeners
import (
"io"
"log"
"sync"
"time"
)
type CompositeWaitListener struct {
mutex sync.Once
waiter *sync.WaitGroup
items []Listener
}
func NewCompositeWaitShutdownListener(listeners ...Listener) *CompositeWaitListener {
this := NewCompositeWaitListener()
this.items = []Listener{NewShutdownListener(this.Close)}
this.items = append(this.items, listeners...)
return this
}
func NewCompositeWaitDelayedShutdownListener(shutdownDelay time.Duration, listeners ...Listener) *CompositeWaitListener {
this := NewCompositeWaitShutdownListener(listeners...)
if sl, ok := this.items[0].(*ShutdownListener); ok {
sl.shutdown = func() {
if shutdownDelay.Nanoseconds() > 0 {
log.Printf("[INFO] Shutdown delay [%s].\n", shutdownDelay)
time.Sleep(shutdownDelay)
}
this.Close() //default shutdown() in NewCompositeWaitShutdownListener()
}
}
return this
}
func NewCompositeWaitListener(listeners ...Listener) *CompositeWaitListener {
return &CompositeWaitListener{
waiter: &sync.WaitGroup{},
items: listeners,
}
}
func (this *CompositeWaitListener) Listen() {
this.waiter.Add(len(this.items))
for _, item := range this.items {
go this.listen(item)
}
this.waiter.Wait()
}
func (this *CompositeWaitListener) listen(listener Listener) {
if listener != nil {
listener.Listen()
}
this.waiter.Done()
}
func (this *CompositeWaitListener) Close() {
this.mutex.Do(this.close)
}
func (this *CompositeWaitListener) close() {
for _, item := range this.items {
if closer, ok := item.(ListenCloser); ok {
closer.Close()
} else if closer, ok := item.(io.Closer); ok {
closer.Close()
}
}
}