1
0
mirror of https://github.com/golang/go synced 2024-09-29 16:14:28 -06:00

time: add Timer.Reset

Fixes #4412.

R=adg, rsc, rogpeppe, andrewdg, bradfitz
CC=golang-dev
https://golang.org/cl/7086050
This commit is contained in:
Volker Dobler 2013-01-17 14:41:53 +11:00 committed by Andrew Gerrand
parent 55740f763f
commit 44ff17e664
2 changed files with 37 additions and 2 deletions

View File

@ -35,10 +35,10 @@ type Timer struct {
// Stop prevents the Timer from firing.
// It returns true if the call stops the timer, false if the timer has already
// expired or stopped.
// expired or been stopped.
// Stop does not close the channel, to prevent a read from the channel succeeding
// incorrectly.
func (t *Timer) Stop() (ok bool) {
func (t *Timer) Stop() bool {
return stopTimer(&t.r)
}
@ -58,6 +58,17 @@ func NewTimer(d Duration) *Timer {
return t
}
// Reset changes the timer to expire after duration d.
// It returns true if the timer had been active, false if the timer had
// expired or been stopped.
func (t *Timer) Reset(d Duration) bool {
when := nano() + int64(d)
active := stopTimer(&t.r)
t.r.when = when
startTimer(&t.r)
return active
}
func sendTime(now int64, c interface{}) {
// Non-blocking send of time on c.
// Used in NewTimer, it cannot block anyway (buffer).

View File

@ -245,3 +245,27 @@ func TestSleepZeroDeadlock(t *testing.T) {
}
<-c
}
func TestReset(t *testing.T) {
t0 := NewTimer(100 * Millisecond)
Sleep(50 * Millisecond)
if t0.Reset(150*Millisecond) != true {
t.Fatalf("resetting unfired timer returned false")
}
Sleep(100 * Millisecond)
select {
case <-t0.C:
t.Fatalf("timer fired early")
default:
}
Sleep(100 * Millisecond)
select {
case <-t0.C:
default:
t.Fatalf("reset timer did not fire")
}
if t0.Reset(50*Millisecond) != false {
t.Fatalf("resetting expired timer returned true")
}
}