You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
720 B

  1. package common
  2. import (
  3. "sync/atomic"
  4. "time"
  5. )
  6. /* Throttler */
  7. type Throttler struct {
  8. Ch chan struct{}
  9. quit chan struct{}
  10. dur time.Duration
  11. timer *time.Timer
  12. isSet uint32
  13. }
  14. func NewThrottler(dur time.Duration) *Throttler {
  15. var ch = make(chan struct{})
  16. var quit = make(chan struct{})
  17. var t = &Throttler{Ch: ch, dur: dur, quit: quit}
  18. t.timer = time.AfterFunc(dur, t.fireHandler)
  19. return t
  20. }
  21. func (t *Throttler) fireHandler() {
  22. select {
  23. case t.Ch <- struct{}{}:
  24. atomic.StoreUint32(&t.isSet, 0)
  25. case <-t.quit:
  26. }
  27. }
  28. func (t *Throttler) Set() {
  29. if atomic.CompareAndSwapUint32(&t.isSet, 0, 1) {
  30. t.timer.Reset(t.dur)
  31. }
  32. }
  33. func (t *Throttler) Stop() bool {
  34. close(t.quit)
  35. return t.timer.Stop()
  36. }