forked from herryg91/gobatch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
membatch.go
55 lines (47 loc) · 994 Bytes
/
membatch.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
package gobatch
import (
"sync"
"time"
)
func NewMemoryBatch(flushMaxSize int, flushMaxWait time.Duration, callback BatchFn, workerSize int) *Batch {
instance := &Batch{
maxSize: flushMaxSize,
maxWait: flushMaxWait,
items: make([]interface{}, 0, flushMaxSize),
doFn: callback,
mutex: &sync.RWMutex{},
flushChan: make(chan []interface{}, workerSize),
}
instance.setFlushWorker(workerSize)
go instance.runFlushByTime()
return instance
}
func (b *Batch) Insert(data interface{}) {
b.mutex.Lock()
defer b.mutex.Unlock()
b.items = append(b.items, data)
if len(b.items) >= b.maxSize {
b.Flush()
}
}
func (b *Batch) runFlushByTime() {
for {
select {
case <-time.Tick(b.maxWait):
b.mutex.Lock()
b.Flush()
b.mutex.Unlock()
}
}
}
func (b *Batch) Flush() {
if len(b.items) <= 0 {
return
}
copiedItems := make([]interface{}, len(b.items))
for idx, i := range b.items {
copiedItems[idx] = i
}
b.items = b.items[:0]
b.flushChan <- copiedItems
}