mirror of https://github.com/k3s-io/k3s
make util.Until return immediately if stop is written inside the loop
parent
f64780d6eb
commit
8b9809291b
|
@ -114,17 +114,22 @@ func Forever(f func(), period time.Duration) {
|
||||||
// stop channel is already closed. Pass NeverStop to Until if you
|
// stop channel is already closed. Pass NeverStop to Until if you
|
||||||
// don't want it stop.
|
// don't want it stop.
|
||||||
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
|
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
|
||||||
|
select {
|
||||||
|
case <-stopCh:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
|
||||||
case <-stopCh:
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
func() {
|
func() {
|
||||||
defer HandleCrash()
|
defer HandleCrash()
|
||||||
f()
|
f()
|
||||||
}()
|
}()
|
||||||
time.Sleep(period)
|
select {
|
||||||
|
case <-stopCh:
|
||||||
|
return
|
||||||
|
case <-time.After(period):
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -24,6 +24,7 @@ import (
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/ghodss/yaml"
|
"github.com/ghodss/yaml"
|
||||||
)
|
)
|
||||||
|
@ -48,6 +49,17 @@ func TestUntil(t *testing.T) {
|
||||||
<-called
|
<-called
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUntilReturnsImmediately(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
ch := make(chan struct{})
|
||||||
|
Until(func() {
|
||||||
|
close(ch)
|
||||||
|
}, 30*time.Second, ch)
|
||||||
|
if now.Add(25 * time.Second).Before(time.Now()) {
|
||||||
|
t.Errorf("Until did not return immediately when the stop chan was closed inside the func")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestHandleCrash(t *testing.T) {
|
func TestHandleCrash(t *testing.T) {
|
||||||
count := 0
|
count := 0
|
||||||
expect := 10
|
expect := 10
|
||||||
|
|
Loading…
Reference in New Issue