delayexecutor.go 941 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package executors
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/threading"
  6. )
  7. // A DelayExecutor delays a tasks on given delay interval.
  8. type DelayExecutor struct {
  9. fn func()
  10. delay time.Duration
  11. triggered bool
  12. lock sync.Mutex
  13. }
  14. // NewDelayExecutor returns a DelayExecutor with given fn and delay.
  15. func NewDelayExecutor(fn func(), delay time.Duration) *DelayExecutor {
  16. return &DelayExecutor{
  17. fn: fn,
  18. delay: delay,
  19. }
  20. }
  21. // Trigger triggers the task to be executed after given delay, safe to trigger more than once.
  22. func (de *DelayExecutor) Trigger() {
  23. de.lock.Lock()
  24. defer de.lock.Unlock()
  25. if de.triggered {
  26. return
  27. }
  28. de.triggered = true
  29. threading.GoSafe(func() {
  30. timer := time.NewTimer(de.delay)
  31. defer timer.Stop()
  32. <-timer.C
  33. // set triggered to false before calling fn to ensure no triggers are missed.
  34. de.lock.Lock()
  35. de.triggered = false
  36. de.lock.Unlock()
  37. de.fn()
  38. })
  39. }