lessexecutor.go 872 B

123456789101112131415161718192021222324252627282930313233343536
  1. package executors
  2. import (
  3. "time"
  4. "git.i2edu.net/i2/go-zero/core/syncx"
  5. "git.i2edu.net/i2/go-zero/core/timex"
  6. )
  7. // A LessExecutor is an executor to limit execution once within given time interval.
  8. type LessExecutor struct {
  9. threshold time.Duration
  10. lastTime *syncx.AtomicDuration
  11. }
  12. // NewLessExecutor returns a LessExecutor with given threshold as time interval.
  13. func NewLessExecutor(threshold time.Duration) *LessExecutor {
  14. return &LessExecutor{
  15. threshold: threshold,
  16. lastTime: syncx.NewAtomicDuration(),
  17. }
  18. }
  19. // DoOrDiscard executes or discards the task depends on if
  20. // another task was executed within the time interval.
  21. func (le *LessExecutor) DoOrDiscard(execute func()) bool {
  22. now := timex.Now()
  23. lastTime := le.lastTime.Load()
  24. if lastTime == 0 || lastTime+le.threshold < now {
  25. le.lastTime.Set(now)
  26. execute()
  27. return true
  28. }
  29. return false
  30. }