forked from ethersphere/bee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait.go
42 lines (34 loc) · 1.01 KB
/
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
// Copyright 2022 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spinlock
import (
"errors"
"time"
)
var ErrTimedOut = errors.New("timed out waiting for condition")
// Wait blocks execution until condition is satisfied or until it times out.
func Wait(timeoutDur time.Duration, cond func() bool) error {
return WaitWithInterval(timeoutDur, time.Millisecond*20, cond)
}
// WaitWithInterval blocks execution until condition is satisfied or until it times out.
// Condition is checked on specified checkIntervalDur.
func WaitWithInterval(timeoutDur, checkIntervalDur time.Duration, cond func() bool) error {
timeout := time.NewTimer(timeoutDur)
defer timeout.Stop()
condCheckTicker := time.NewTicker(checkIntervalDur)
defer condCheckTicker.Stop()
for {
select {
case <-timeout.C:
if cond() {
return nil
}
return ErrTimedOut
case <-condCheckTicker.C:
if cond() {
return nil
}
}
}
}