diff --git a/clock.go b/clock.go index 4e8a3e3..6a4edb2 100644 --- a/clock.go +++ b/clock.go @@ -317,6 +317,13 @@ func (t *Ticker) Stop() { } } +// Reset resets the ticker to a new duration. +func (t *Ticker) Reset(dur time.Duration) { + if t.ticker != nil { + t.ticker.Reset(dur) + } +} + type internalTicker Ticker func (t *internalTicker) Next() time.Time { return t.next } diff --git a/clock_test.go b/clock_test.go index 275f5b9..36296f4 100644 --- a/clock_test.go +++ b/clock_test.go @@ -124,21 +124,33 @@ func TestClock_Ticker(t *testing.T) { // Ensure that the clock's ticker can stop correctly. func TestClock_Ticker_Stp(t *testing.T) { + ticker := New().Ticker(20 * time.Millisecond) + <-ticker.C + ticker.Stop() + select { + case <-ticker.C: + t.Fatal("unexpected send") + case <-time.After(30 * time.Millisecond): + } +} + +// Ensure that the clock's ticker can reset correctly. +func TestClock_Ticker_Rst(t *testing.T) { var ok bool go func() { - time.Sleep(10 * time.Millisecond) + time.Sleep(30 * time.Millisecond) ok = true }() gosched() ticker := New().Ticker(20 * time.Millisecond) <-ticker.C - ticker.Stop() - select { - case <-ticker.C: - t.Fatal("unexpected send") - case <-time.After(30 * time.Millisecond): + ticker.Reset(5 * time.Millisecond) + <-ticker.C + if ok { + t.Fatal("too late") } + ticker.Stop() } // Ensure that the clock's timer waits correctly. @@ -167,12 +179,6 @@ func TestClock_Timer(t *testing.T) { // Ensure that the clock's timer can be stopped. func TestClock_Timer_Stop(t *testing.T) { - var ok bool - go func() { - time.Sleep(10 * time.Millisecond) - ok = true - }() - timer := New().Timer(20 * time.Millisecond) if !timer.Stop() { t.Fatal("timer not running") diff --git a/go.mod b/go.mod index 2785ed6..758903a 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/benbjohnson/clock -go 1.13 +go 1.15