sometimes.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2022 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package rate
  5. import (
  6. "sync"
  7. "time"
  8. )
  9. // Sometimes will perform an action occasionally. The First, Every, and
  10. // Interval fields govern the behavior of Do, which performs the action.
  11. // A zero Sometimes value will perform an action exactly once.
  12. //
  13. // # Example: logging with rate limiting
  14. //
  15. // var sometimes = rate.Sometimes{First: 3, Interval: 10*time.Second}
  16. // func Spammy() {
  17. // sometimes.Do(func() { log.Info("here I am!") })
  18. // }
  19. type Sometimes struct {
  20. First int // if non-zero, the first N calls to Do will run f.
  21. Every int // if non-zero, every Nth call to Do will run f.
  22. Interval time.Duration // if non-zero and Interval has elapsed since f's last run, Do will run f.
  23. mu sync.Mutex
  24. count int // number of Do calls
  25. last time.Time // last time f was run
  26. }
  27. // Do runs the function f as allowed by First, Every, and Interval.
  28. //
  29. // The model is a union (not intersection) of filters. The first call to Do
  30. // always runs f. Subsequent calls to Do run f if allowed by First or Every or
  31. // Interval.
  32. //
  33. // A non-zero First:N causes the first N Do(f) calls to run f.
  34. //
  35. // A non-zero Every:M causes every Mth Do(f) call, starting with the first, to
  36. // run f.
  37. //
  38. // A non-zero Interval causes Do(f) to run f if Interval has elapsed since
  39. // Do last ran f.
  40. //
  41. // Specifying multiple filters produces the union of these execution streams.
  42. // For example, specifying both First:N and Every:M causes the first N Do(f)
  43. // calls and every Mth Do(f) call, starting with the first, to run f. See
  44. // Examples for more.
  45. //
  46. // If Do is called multiple times simultaneously, the calls will block and run
  47. // serially. Therefore, Do is intended for lightweight operations.
  48. //
  49. // Because a call to Do may block until f returns, if f causes Do to be called,
  50. // it will deadlock.
  51. func (s *Sometimes) Do(f func()) {
  52. s.mu.Lock()
  53. defer s.mu.Unlock()
  54. if s.count == 0 ||
  55. (s.First > 0 && s.count < s.First) ||
  56. (s.Every > 0 && s.count%s.Every == 0) ||
  57. (s.Interval > 0 && time.Since(s.last) >= s.Interval) {
  58. f()
  59. s.last = time.Now()
  60. }
  61. s.count++
  62. }