-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel-worker.go
68 lines (57 loc) · 1.36 KB
/
channel-worker.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
package swissknife
type ChannelWorker struct {
MaxCapacity int
Events chan interface{}
EventHandlerCallback func(event interface{})
ProcessingEvents bool
IsFinished bool
isAsyncMode bool
}
func NewChannelWorker(callback func(event interface{}), maxCapacity int) *ChannelWorker {
return &ChannelWorker{
MaxCapacity: maxCapacity,
Events: make(chan interface{}, maxCapacity),
EventHandlerCallback: callback,
}
}
func (w *ChannelWorker) SetAsync(asyncMode bool) *ChannelWorker {
w.isAsyncMode = asyncMode
return w
}
func (w *ChannelWorker) AddEvent(event interface{}) {
// check channel capacity
if len(w.Events) >= w.MaxCapacity {
return
}
// add message to channel
w.Events <- event
}
// Start handle events
// NOTE: it's blocking method
func (w *ChannelWorker) Start() {
w.ProcessingEvents = true
w.handleEvents()
}
func (w *ChannelWorker) Stop() {
w.ProcessingEvents = false
}
func (w *ChannelWorker) GetMessagesAvailableCount() int {
return len(w.Events)
}
func (w *ChannelWorker) handleEvents() {
w.IsFinished = false
for w.ProcessingEvents {
for event := range w.Events {
if !w.ProcessingEvents {
break
}
if w.isAsyncMode {
go w.EventHandlerCallback(event)
} else {
w.EventHandlerCallback(event)
}
}
}
w.ProcessingEvents = false
w.IsFinished = true
}