Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make util.Until return immediately if stop is written inside the loop #16829

Merged
merged 1 commit into from
Nov 5, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 11 additions & 6 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,22 @@ func Forever(f func(), period time.Duration) {
// stop channel is already closed. Pass NeverStop to Until if you
// don't want it stop.
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
select {
case <-stopCh:
return
default:
}

for {
select {
case <-stopCh:
return
default:
}
func() {
defer HandleCrash()
f()
}()
time.Sleep(period)
select {
case <-stopCh:
return
case <-time.After(period):
}
}
}

Expand Down
12 changes: 12 additions & 0 deletions pkg/util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"reflect"
"strings"
"testing"
"time"

"github.com/ghodss/yaml"
)
Expand All @@ -48,6 +49,17 @@ func TestUntil(t *testing.T) {
<-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) {
count := 0
expect := 10
Expand Down