1 /* 2 Copyright 2023 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 wait 18 19 import ( 20 "context" 21 "sync" 22 "time" 23 24 "k8s.io/utils/clock" 25 ) 26 27 // DelayFunc returns the next time interval to wait. 28 type DelayFunc func() time.Duration 29 30 // Timer takes an arbitrary delay function and returns a timer that can handle arbitrary interval changes. 31 // Use Backoff{...}.Timer() for simple delays and more efficient timers. 32 func (fn DelayFunc) Timer(c clock.Clock) Timer { 33 return &variableTimer{fn: fn, new: c.NewTimer} 34 } 35 36 // Until takes an arbitrary delay function and runs until cancelled or the condition indicates exit. This 37 // offers all of the functionality of the methods in this package. 38 func (fn DelayFunc) Until(ctx context.Context, immediate, sliding bool, condition ConditionWithContextFunc) error { 39 return loopConditionUntilContext(ctx, &variableTimer{fn: fn, new: internalClock.NewTimer}, immediate, sliding, condition) 40 } 41 42 // Concurrent returns a version of this DelayFunc that is safe for use by multiple goroutines that 43 // wish to share a single delay timer. 44 func (fn DelayFunc) Concurrent() DelayFunc { 45 var lock sync.Mutex 46 return func() time.Duration { 47 lock.Lock() 48 defer lock.Unlock() 49 return fn() 50 } 51 } 52