-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_handler.go
85 lines (73 loc) · 1.64 KB
/
batch_handler.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
package handler
import (
"fmt"
"time"
)
type emptyHandler struct{}
func (h *emptyHandler) HandleMessage(v interface{}) {}
var (
gEmptyHandler = new(emptyHandler)
)
type batchHandlerRoutine struct {
queue *messageQueue
quit chan struct{}
handler BatchHandler
}
func NewBatchHandlerRoutine(handler BatchHandler) *batchHandlerRoutine {
return &batchHandlerRoutine{
quit: make(chan struct{}),
handler: handler,
}
}
func (r *batchHandlerRoutine) Running() bool {
return r.queue != nil
}
func (r *batchHandlerRoutine) Start() error {
if r.queue != nil {
return fmt.Errorf("batch handler routine is already started")
}
r.queue = newMessageQueue()
go func() {
for {
m := r.queue.dequeue2()
if m.handler == nil {
r.quit <- struct{}{}
r.queue = nil
return
}
v := make([]interface{}, 0)
for m != nil {
v = append(v, m.value)
m = m.next
}
r.handler.HandleMessages(v)
}
}()
return nil
}
func (r *batchHandlerRoutine) Stop() error {
if r.queue == nil {
return fmt.Errorf("handler routine is already stopped")
}
m := newMessage(nil)
m.handler = nil
r.queue.enqueue(m)
<-r.quit
return nil
}
func (r *batchHandlerRoutine) SendMessage(v interface{}) error {
return r.SendMessageAt(v, time.Now())
}
func (r *batchHandlerRoutine) SendMessageAt(v interface{}, when time.Time) error {
if r.queue == nil {
return fmt.Errorf("handler routine is not running")
}
m := newMessage(v)
m.handler = gEmptyHandler
m.when = when
r.queue.enqueue(m)
return nil
}
func (r *batchHandlerRoutine) SendMessageDelayed(v interface{}, delay time.Duration) error {
return r.SendMessageAt(v, time.Now().Add(delay))
}