atmostevery.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2020 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package internal
  14. import (
  15. "sync"
  16. "time"
  17. )
  18. // AtMostEvery will never run the method more than once every specified
  19. // duration.
  20. type AtMostEvery struct {
  21. delay time.Duration
  22. lastCall time.Time
  23. mutex sync.Mutex
  24. }
  25. // NewAtMostEvery creates a new AtMostEvery, that will run the method at
  26. // most every given duration.
  27. func NewAtMostEvery(delay time.Duration) *AtMostEvery {
  28. return &AtMostEvery{
  29. delay: delay,
  30. }
  31. }
  32. // updateLastCall returns true if the lastCall time has been updated,
  33. // false if it was too early.
  34. func (s *AtMostEvery) updateLastCall() bool {
  35. s.mutex.Lock()
  36. defer s.mutex.Unlock()
  37. if time.Since(s.lastCall) < s.delay {
  38. return false
  39. }
  40. s.lastCall = time.Now()
  41. return true
  42. }
  43. // Do will run the method if enough time has passed, and return true.
  44. // Otherwise, it does nothing and returns false.
  45. func (s *AtMostEvery) Do(fn func()) bool {
  46. if !s.updateLastCall() {
  47. return false
  48. }
  49. fn()
  50. return true
  51. }