lessexecutor.go 598 B

1234567891011121314151617181920212223242526272829303132
  1. package executors
  2. import (
  3. "time"
  4. "github.com/tal-tech/go-zero/core/syncx"
  5. "github.com/tal-tech/go-zero/core/timex"
  6. )
  7. type LessExecutor struct {
  8. threshold time.Duration
  9. lastTime *syncx.AtomicDuration
  10. }
  11. func NewLessExecutor(threshold time.Duration) *LessExecutor {
  12. return &LessExecutor{
  13. threshold: threshold,
  14. lastTime: syncx.NewAtomicDuration(),
  15. }
  16. }
  17. func (le *LessExecutor) DoOrDiscard(execute func()) bool {
  18. now := timex.Now()
  19. lastTime := le.lastTime.Load()
  20. if lastTime == 0 || lastTime+le.threshold < now {
  21. le.lastTime.Set(now)
  22. execute()
  23. return true
  24. }
  25. return false
  26. }