github.com/ethersphere/bee/v2@v2.2.0/pkg/spinlock/wait.go (about) 1 // Copyright 2022 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package spinlock 6 7 import ( 8 "errors" 9 "time" 10 ) 11 12 var ErrTimedOut = errors.New("timed out waiting for condition") 13 14 // Wait blocks execution until condition is satisfied or until it times out. 15 func Wait(timeoutDur time.Duration, cond func() bool) error { 16 return WaitWithInterval(timeoutDur, time.Millisecond*50, cond) 17 } 18 19 // WaitWithInterval blocks execution until condition is satisfied or until it times out. 20 // Condition is checked on specified checkIntervalDur. 21 func WaitWithInterval(timeoutDur, checkIntervalDur time.Duration, cond func() bool) error { 22 timeout := time.NewTimer(timeoutDur) 23 defer timeout.Stop() 24 25 condCheckTicker := time.NewTicker(checkIntervalDur) 26 defer condCheckTicker.Stop() 27 28 for { 29 select { 30 case <-timeout.C: 31 if cond() { 32 return nil 33 } 34 return ErrTimedOut 35 36 case <-condCheckTicker.C: 37 if cond() { 38 return nil 39 } 40 } 41 } 42 }