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