Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

Commit

Permalink
Merge pull request #25 from mqnfred/master
Browse files Browse the repository at this point in the history
Introduce ticker Reset
  • Loading branch information
benbjohnson committed Nov 24, 2020
2 parents d30813f + 421f858 commit 307483a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 13 deletions.
7 changes: 7 additions & 0 deletions clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
30 changes: 18 additions & 12 deletions clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/benbjohnson/clock

go 1.13
go 1.15

0 comments on commit 307483a

Please sign in to comment.