mirror of
https://github.com/scroll-tech/scroll.git
synced 2026-01-14 16:37:56 -05:00
Co-authored-by: vincent <419436363@qq.com> Co-authored-by: colinlyguo <651734127@qq.com> Co-authored-by: maskpp <maskpp266@gmail.com>
45 lines
798 B
Go
45 lines
798 B
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
)
|
|
|
|
// TryTimes try run several times until the function return true.
|
|
func TryTimes(times int, run func() bool) {
|
|
for i := 0; i < times; i++ {
|
|
if run() {
|
|
return
|
|
}
|
|
time.Sleep(time.Millisecond * 500)
|
|
}
|
|
}
|
|
|
|
// LoopWithContext Run the f func with context periodically.
|
|
func LoopWithContext(ctx context.Context, period time.Duration, f func(ctx context.Context)) {
|
|
tick := time.NewTicker(period)
|
|
defer tick.Stop()
|
|
for ; ; <-tick.C {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
default:
|
|
f(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Loop Run the f func periodically.
|
|
func Loop(ctx context.Context, period time.Duration, f func()) {
|
|
tick := time.NewTicker(period)
|
|
defer tick.Stop()
|
|
for ; ; <-tick.C {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
default:
|
|
f()
|
|
}
|
|
}
|
|
}
|