forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lessexecutor.go
36 lines (30 loc) · 886 Bytes
/
lessexecutor.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
package executors
import (
"time"
"github.com/xiaoshouchen/go-zero/core/syncx"
"github.com/xiaoshouchen/go-zero/core/timex"
)
// A LessExecutor is an executor to limit execution once within given time interval.
type LessExecutor struct {
threshold time.Duration
lastTime *syncx.AtomicDuration
}
// NewLessExecutor returns a LessExecutor with given threshold as time interval.
func NewLessExecutor(threshold time.Duration) *LessExecutor {
return &LessExecutor{
threshold: threshold,
lastTime: syncx.NewAtomicDuration(),
}
}
// DoOrDiscard executes or discards the task depends on if
// another task was executed within the time interval.
func (le *LessExecutor) DoOrDiscard(execute func()) bool {
now := timex.Now()
lastTime := le.lastTime.Load()
if lastTime == 0 || lastTime+le.threshold < now {
le.lastTime.Set(now)
execute()
return true
}
return false
}