qingcloud-sdk-go/utils/wait.go

58 lines
1.3 KiB
Go
Raw Normal View History

2017-01-17 09:24:29 +00:00
package utils
import (
"fmt"
"time"
)
2017-07-12 10:33:00 +00:00
// TimeoutError An Error represents a timeout error.
2017-07-12 10:05:43 +00:00
type TimeoutError struct {
timeout time.Duration
}
2017-08-01 11:42:29 +00:00
2017-07-12 10:33:00 +00:00
// Error message
2017-08-01 11:42:29 +00:00
func (e *TimeoutError) Error() string { return fmt.Sprintf("Wait timeout [%s] ", e.timeout) }
2017-07-12 10:33:00 +00:00
// Timeout duration
2017-07-12 10:05:43 +00:00
func (e *TimeoutError) Timeout() time.Duration { return e.timeout }
2017-07-12 10:33:00 +00:00
// NewTimeoutError create a new TimeoutError
2017-07-12 10:05:43 +00:00
func NewTimeoutError(timeout time.Duration) *TimeoutError {
return &TimeoutError{timeout: timeout}
}
2017-03-27 02:57:47 +00:00
// WaitForSpecificOrError wait a function return true or error.
2017-01-17 09:24:29 +00:00
func WaitForSpecificOrError(f func() (bool, error), timeout time.Duration, waitInterval time.Duration) error {
ticker := time.NewTicker(waitInterval)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-ticker.C:
stop, err := f()
if err != nil {
return err
}
if stop {
return nil
}
case <-timer.C:
2017-07-12 10:05:43 +00:00
return NewTimeoutError(timeout)
2017-01-17 09:24:29 +00:00
}
}
}
2017-03-27 02:57:47 +00:00
// WaitForSpecific wait a function return true.
2017-01-17 09:24:29 +00:00
func WaitForSpecific(f func() bool, timeout time.Duration, waitInterval time.Duration) error {
return WaitForSpecificOrError(func() (bool, error) {
return f(), nil
}, timeout, waitInterval)
}
2017-03-27 02:57:47 +00:00
// WaitFor wait a function return true.
2017-01-17 09:24:29 +00:00
func WaitFor(f func() bool) error {
return WaitForSpecific(f, 180*time.Second, 3*time.Second)
}