-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaitfor.go
52 lines (43 loc) · 929 Bytes
/
waitfor.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 waitfor
import (
"errors"
"time"
"golang.org/x/net/context"
)
var ErrTimeoutExceeded = errors.New("timeout exceeded")
type Check func() bool
func ConditionWithTimeout(condition Check, interval, timeout time.Duration) error {
errChan := make(chan error)
ctx, _ := context.WithTimeout(context.Background(), timeout)
go Condition(condition, interval, errChan, ctx)
select {
case err := <-errChan:
return handleErr(err)
case <-ctx.Done():
return handleErr(ctx.Err())
}
}
func Condition(condition Check, interval time.Duration, errChan chan error, ctx context.Context) {
if condition() {
errChan <- nil
return
}
for {
select {
case <-ctx.Done():
errChan <- ctx.Err()
return
case <-time.After(interval):
if condition() {
errChan <- nil
return
}
}
}
}
func handleErr(err error) error {
if err == context.DeadlineExceeded {
return ErrTimeoutExceeded
}
return err
}