/
wait.go
52 lines (43 loc) · 895 Bytes
/
wait.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package common
import (
"context"
"fmt"
"time"
)
func Wait(interval time.Duration, timeout time.Duration, times int, fn func() (bool, error)) error {
return WaitContext(context.Background(), interval, timeout, times, fn)
}
func WaitContext(ctx context.Context, interval time.Duration, timeout time.Duration, times int, fn func() (bool, error)) error {
successes := 0
errors := 0
start := time.Now().UTC()
tick := time.NewTicker(interval)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-tick.C:
if start.Add(timeout).Before(time.Now().UTC()) {
return fmt.Errorf("timeout")
}
success, err := fn()
if err != nil {
errors += 1
} else {
errors = 0
}
if errors >= times {
return err
}
if success {
successes += 1
} else {
successes = 0
}
if successes >= times {
return nil
}
}
}
}