You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/executors/lessexecutor.go

37 lines
880 B
Go

4 years ago
package executors
import (
"time"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
4 years ago
)
// A LessExecutor is an executor to limit execution once within given time interval.
4 years ago
type LessExecutor struct {
threshold time.Duration
lastTime *syncx.AtomicDuration
}
// NewLessExecutor returns a LessExecutor with given threshold as time interval.
4 years ago
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.
4 years ago
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
}