-
Notifications
You must be signed in to change notification settings - Fork 74
/
rate.go
50 lines (41 loc) · 829 Bytes
/
rate.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
package paxi
import (
"sync"
"time"
)
// Limiter limits operation rate when used with Wait function
type Limiter struct {
sync.Mutex
last time.Time
sleep time.Duration
interval time.Duration
slack time.Duration
}
// NewLimiter creates a new rate limiter, where rate is operations per second
func NewLimiter(rate int) *Limiter {
return &Limiter{
interval: time.Second / time.Duration(rate),
slack: -10 * time.Second / time.Duration(rate),
}
}
// Wait blocks for the limit
func (l *Limiter) Wait() {
l.Lock()
defer l.Unlock()
now := time.Now()
if l.last.IsZero() {
l.last = now
return
}
l.sleep += l.interval - now.Sub(l.last)
if l.sleep < l.slack {
l.sleep = l.slack
}
if l.sleep > 0 {
time.Sleep(l.sleep)
l.last = now.Add(l.sleep)
l.sleep = 0
} else {
l.last = now
}
}