-
Notifications
You must be signed in to change notification settings - Fork 0
/
batcher.go
55 lines (44 loc) · 854 Bytes
/
batcher.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 batcher
import (
"errors"
"time"
)
type Batcher struct {
batchSize int
delay time.Duration
batchCount int
currentBatch int
maxLen int
}
func New(itemsLen, batchSize int, delay time.Duration) *Batcher {
return &Batcher{
batchSize: batchSize,
delay: delay,
batchCount: (itemsLen + batchSize - 1) / batchSize,
maxLen: itemsLen,
}
}
func (b *Batcher) Next() error {
defer func() {
b.currentBatch++
}()
if b.currentBatch >= b.batchCount {
return errors.New("end of batch")
}
if b.currentBatch > 0 {
time.Sleep(b.delay)
}
return nil
}
func (b *Batcher) StartKey() int {
if b.currentBatch == 0 {
return 0
}
return (b.currentBatch - 1) * b.batchSize
}
func (b *Batcher) EndKey() int {
if b.currentBatch == b.batchCount {
return b.maxLen
}
return b.StartKey() + b.batchSize
}