-
Notifications
You must be signed in to change notification settings - Fork 43
/
cd.go
64 lines (53 loc) · 922 Bytes
/
cd.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
package utils
import (
"context"
"time"
)
type CoolDown struct {
du time.Duration
ctx context.Context
cancel func()
coreChan chan interface{}
}
func NewCoolDownContext(d time.Duration, ctx context.Context) *CoolDown {
cd := &CoolDown{du: d}
cd.ctx, cd.cancel = context.WithCancel(ctx)
cd.coreChan = make(chan interface{}, 0)
go func() {
exitForCtx := func() {
select {
case <-cd.ctx.Done():
return
default:
}
}
for {
exitForCtx()
cd.coreChan <- nil
time.Sleep(cd.du)
exitForCtx()
}
}()
return cd
}
func NewCoolDown(d time.Duration) *CoolDown {
return NewCoolDownContext(d, context.Background())
}
func (c *CoolDown) Reset(d time.Duration) {
c.du = d
}
func (c *CoolDown) Do(f func()) {
select {
case <-c.coreChan:
f()
default:
}
}
func (c *CoolDown) DoOr(f func(), fallback func()) {
select {
case <-c.coreChan:
f()
default:
fallback()
}
}