-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththrottle.go
70 lines (57 loc) · 1.14 KB
/
throttle.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
package window
import (
"fmt"
"time"
)
type (
throttle struct {
concurrent chan struct{}
rate chan struct{}
ticker *time.Ticker
}
)
func NewThrottle(concurrent int, rate int, interval time.Duration) *throttle {
t := &throttle{
concurrent: make(chan struct{}, concurrent),
rate: make(chan struct{}, rate),
ticker: time.NewTicker(interval),
}
go func() {
for range t.ticker.C {
for i := 0; i < cap(t.rate); i++ {
select {
case <-t.rate:
default:
break
}
}
}
}()
return t
}
func (t *throttle) do(name string, f func() error) chan error {
errchan := make(chan error, 1)
go func() {
var err error
t.concurrent <- struct{}{}
t.rate <- struct{}{}
defer func() {
<-t.concurrent
// if e := recover(); e != nil {
// errchan <- fmt.Errorf("%s panic: %v", name, e)
// } else
if err != nil {
errchan <- fmt.Errorf("%s error: %v", name, err)
} else {
errchan <- nil
}
}()
// start := time.Now()
err = f()
// fmt.Fprintf(os.Stderr, "%s completed in %s\n", name, time.Since(start))
}()
return errchan
}
func (t *throttle) stop() {
t.ticker.Stop()
}