Skip to content

Commit 44ff17e

Browse files
vdobleradg
authored andcommitted
time: add Timer.Reset
Fixes golang#4412. R=adg, rsc, rogpeppe, andrewdg, bradfitz CC=golang-dev https://golang.org/cl/7086050
1 parent 55740f7 commit 44ff17e

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/pkg/time/sleep.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ type Timer struct {
3535

3636
// Stop prevents the Timer from firing.
3737
// It returns true if the call stops the timer, false if the timer has already
38-
// expired or stopped.
38+
// expired or been stopped.
3939
// Stop does not close the channel, to prevent a read from the channel succeeding
4040
// incorrectly.
41-
func (t *Timer) Stop() (ok bool) {
41+
func (t *Timer) Stop() bool {
4242
return stopTimer(&t.r)
4343
}
4444

@@ -58,6 +58,17 @@ func NewTimer(d Duration) *Timer {
5858
return t
5959
}
6060

61+
// Reset changes the timer to expire after duration d.
62+
// It returns true if the timer had been active, false if the timer had
63+
// expired or been stopped.
64+
func (t *Timer) Reset(d Duration) bool {
65+
when := nano() + int64(d)
66+
active := stopTimer(&t.r)
67+
t.r.when = when
68+
startTimer(&t.r)
69+
return active
70+
}
71+
6172
func sendTime(now int64, c interface{}) {
6273
// Non-blocking send of time on c.
6374
// Used in NewTimer, it cannot block anyway (buffer).

src/pkg/time/sleep_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,27 @@ func TestSleepZeroDeadlock(t *testing.T) {
245245
}
246246
<-c
247247
}
248+
249+
func TestReset(t *testing.T) {
250+
t0 := NewTimer(100 * Millisecond)
251+
Sleep(50 * Millisecond)
252+
if t0.Reset(150*Millisecond) != true {
253+
t.Fatalf("resetting unfired timer returned false")
254+
}
255+
Sleep(100 * Millisecond)
256+
select {
257+
case <-t0.C:
258+
t.Fatalf("timer fired early")
259+
default:
260+
}
261+
Sleep(100 * Millisecond)
262+
select {
263+
case <-t0.C:
264+
default:
265+
t.Fatalf("reset timer did not fire")
266+
}
267+
268+
if t0.Reset(50*Millisecond) != false {
269+
t.Fatalf("resetting expired timer returned true")
270+
}
271+
}

0 commit comments

Comments
 (0)