diff --git a/watchdog.go b/watchdog.go index 03ca2e6..466161f 100644 --- a/watchdog.go +++ b/watchdog.go @@ -267,9 +267,19 @@ func SystemDriven(limit uint64, frequency time.Duration, policyCtor PolicyCtor) // initialize the threshold. renewThreshold() + // initialize an empty timer. + timer := Clock.Timer(0) + stopTimer := func() { + if !timer.Stop() { + <-timer.C + } + } + for { + timer.Reset(frequency) + select { - case <-Clock.After(frequency): + case <-timer.C: // get the current usage. if err := sysmemFn(&sysmem); err != nil { Logger.Warnf("failed to obtain system memory stats; err: %s", err) @@ -290,7 +300,10 @@ func SystemDriven(limit uint64, frequency time.Duration, policyCtor PolicyCtor) renewThreshold() + stopTimer() + case <-_watchdog.closing: + stopTimer() return } } diff --git a/watchdog_test.go b/watchdog_test.go index c456032..67bb6e3 100644 --- a/watchdog_test.go +++ b/watchdog_test.go @@ -52,7 +52,7 @@ func TestControl(t *testing.T) { var ms runtime.MemStats runtime.ReadMemStats(&ms) - require.LessOrEqual(t, ms.NumGC, uint32(8)) // a maximum of 8 GCs should've happened. + require.LessOrEqual(t, ms.NumGC, uint32(5)) // a maximum of 8 GCs should've happened. require.Zero(t, ms.NumForcedGC) // no forced GCs. } @@ -91,7 +91,7 @@ func TestHeapDriven(t *testing.T) { var ms runtime.MemStats runtime.ReadMemStats(&ms) - require.GreaterOrEqual(t, ms.NumGC, uint32(10)) // over 12 GCs should've taken place. + require.GreaterOrEqual(t, ms.NumGC, uint32(9)) // over 9 GCs should've taken place. } func TestSystemDriven(t *testing.T) {