mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-07 06:59:59 +08:00
33 lines
552 B
Go
33 lines
552 B
Go
|
|
package executors
|
||
|
|
|
||
|
|
import (
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"zero/core/syncx"
|
||
|
|
"zero/core/timex"
|
||
|
|
)
|
||
|
|
|
||
|
|
type LessExecutor struct {
|
||
|
|
threshold time.Duration
|
||
|
|
lastTime *syncx.AtomicDuration
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewLessExecutor(threshold time.Duration) *LessExecutor {
|
||
|
|
return &LessExecutor{
|
||
|
|
threshold: threshold,
|
||
|
|
lastTime: syncx.NewAtomicDuration(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
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
|
||
|
|
}
|