delayexecutor.go 718 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package executors
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/threading"
  6. )
  7. type DelayExecutor struct {
  8. fn func()
  9. delay time.Duration
  10. triggered bool
  11. lock sync.Mutex
  12. }
  13. func NewDelayExecutor(fn func(), delay time.Duration) *DelayExecutor {
  14. return &DelayExecutor{
  15. fn: fn,
  16. delay: delay,
  17. }
  18. }
  19. func (de *DelayExecutor) Trigger() {
  20. de.lock.Lock()
  21. defer de.lock.Unlock()
  22. if de.triggered {
  23. return
  24. }
  25. de.triggered = true
  26. threading.GoSafe(func() {
  27. timer := time.NewTimer(de.delay)
  28. defer timer.Stop()
  29. <-timer.C
  30. // set triggered to false before calling fn to ensure no triggers are missed.
  31. de.lock.Lock()
  32. de.triggered = false
  33. de.lock.Unlock()
  34. de.fn()
  35. })
  36. }