-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathevents.go
More file actions
81 lines (72 loc) · 1.32 KB
/
events.go
File metadata and controls
81 lines (72 loc) · 1.32 KB
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
package server
import (
"context"
"os"
"os/signal"
"syscall"
"time"
)
type Event struct {
Ctx context.Context
Cancel context.CancelFunc
}
func NewEvent() *Event {
return NewEventWithContext(context.Background())
}
func NewEventWithContext(ctx context.Context) *Event {
cancelCtx, cancel := context.WithCancel(ctx)
return &Event{
Ctx: cancelCtx,
Cancel: cancel,
}
}
func NewEventWithCancelContext(cancelCtx context.Context, cancel context.CancelFunc) *Event {
return &Event{
Ctx: cancelCtx,
Cancel: cancel,
}
}
func (self *Event) Set() {
self.Cancel()
}
func (self *Event) IsSet() bool {
select {
case <-self.Ctx.Done():
return true
default:
return false
}
}
func (self *Event) WaitForSet(timeout time.Duration) bool {
select {
case <-self.Ctx.Done():
return true
case <-time.After(timeout):
return false
}
}
func (self *Event) SetOnSignals(signalValues ...syscall.Signal) func() {
stopSignal := make(chan os.Signal, len(signalValues))
for _, signalValue := range signalValues {
signal.Notify(stopSignal, signalValue)
}
go HandleError(func() {
for {
select {
case _, ok := <-stopSignal:
if !ok {
return
}
self.Set()
}
}
}, func() {
signal.Stop(stopSignal)
close(stopSignal)
self.Set()
})
return func() {
signal.Stop(stopSignal)
close(stopSignal)
}
}