Skip to content

Commit ae2d551

Browse files
authored
cpu: fix ticker to avoid close early (#40036)
ref #40029
1 parent fdf335e commit ae2d551

File tree

3 files changed

+10
-6
lines changed

3 files changed

+10
-6
lines changed

util/cpu/BUILD.bazel

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ go_test(
2020
name = "cpu_test",
2121
srcs = ["cpu_test.go"],
2222
embed = [":cpu"],
23+
flaky = True,
2324
deps = ["@com_github_stretchr_testify//require"],
2425
)

util/cpu/cpu.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,13 @@ func NewCPUObserver() *Observer {
5656

5757
// Start starts the cpu observer.
5858
func (c *Observer) Start() {
59-
ticker := time.NewTicker(100 * time.Millisecond)
60-
defer ticker.Stop()
6159
c.wg.Add(1)
6260
go func() {
63-
defer c.wg.Done()
61+
ticker := time.NewTicker(100 * time.Millisecond)
62+
defer func() {
63+
ticker.Stop()
64+
c.wg.Done()
65+
}()
6466
for {
6567
select {
6668
case <-ticker.C:

util/cpu/cpu_test.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ func TestCPUValue(t *testing.T) {
4242
}
4343
}()
4444
}
45-
time.Sleep(30 * time.Second)
46-
require.Greater(t, Observer.observe(), 0.0)
47-
require.Less(t, Observer.observe(), 1.0)
45+
Observer.Start()
46+
time.Sleep(5 * time.Second)
47+
require.GreaterOrEqual(t, GetCPUUsage(), 0.0)
48+
require.Less(t, GetCPUUsage(), 1.0)
4849
Observer.Stop()
4950
close(exit)
5051
wg.Wait()

0 commit comments

Comments
 (0)