delay.go 1.7 KB

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