2019-11-02 14:32:58 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-01-21 00:10:00 +00:00
|
|
|
// CheckUntil regularly check a predicate until it's true or time out is reached.
|
2019-11-02 14:32:58 +00:00
|
|
|
func CheckUntil(interval time.Duration, timeout time.Duration, predicate func() (bool, error)) error {
|
2023-01-12 11:30:16 +00:00
|
|
|
timeoutCh := time.After(timeout)
|
|
|
|
|
2019-11-02 14:32:58 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-time.After(interval):
|
|
|
|
predTrue, err := predicate()
|
|
|
|
if predTrue {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-01-12 11:30:16 +00:00
|
|
|
case <-timeoutCh:
|
2021-07-03 22:08:24 +00:00
|
|
|
return fmt.Errorf("timeout of %ds reached", int64(timeout/time.Second))
|
2019-11-02 14:32:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|