forked from ChristophGraham/go-ext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.go
43 lines (38 loc) · 939 Bytes
/
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
package msync
import (
"sync/atomic"
"time"
)
// ThrottleTail returns a function that calls fn() at most every duration, when
// the first call is on the tail of the duration.
func ThrottleTail(duration time.Duration, fn func()) func() {
var lastCall int64
return func() {
last := atomic.LoadInt64(&lastCall)
now := time.Now().UnixNano()
if last > now {
return
}
if atomic.CompareAndSwapInt64(&lastCall, last, now+int64(duration)) {
go func() {
time.Sleep(duration)
fn()
}()
}
}
}
// ThrottleTail returns a function that calls fn() at most every duration, when
// the first call is on the head of the duration.
func ThrottleHead(duration time.Duration, fn func()) func() {
var lastCall int64
return func() {
last := atomic.LoadInt64(&lastCall)
now := time.Now().UnixNano()
if last+int64(duration) > now {
return
}
if atomic.CompareAndSwapInt64(&lastCall, last, now) {
fn()
}
}
}