retry.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. Copyright 2021 The Rook Authors. All rights reserved.
  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 utils
  14. import "time"
  15. // Retry executes the function ('f') 'count' times waiting for 'wait' duration between
  16. // each attempt to run the function. Print the 'description' before all test info messages.
  17. // Returns true the first time function 'f' returns true or false if 'f' never returns true.
  18. func Retry(count uint16, wait time.Duration, description string, f func() bool) bool {
  19. for i := uint16(1); i < count+1; i++ {
  20. if f() {
  21. logger.Infof(description+": TRUE on attempt %d", i)
  22. return true
  23. }
  24. logger.Infof(description+": false on attempt %d. waiting %s seconds to retry", i, wait.String())
  25. time.Sleep(wait)
  26. }
  27. logger.Infof(description+": FALSE on all %d attempts", count)
  28. return false
  29. }