Timer.Reset and channel lifetime

82 views
Skip to first unread message

Wojciech Kaczmarek

unread,
Jun 9, 2026, 1:08:07 PM (2 days ago) Jun 9
to golang-nuts
Hi Gophers.

I'm wondering if the Timer.C channel can be invalidated (recreated) after calling Reset.
In other words, is it safe to store the C channel on side after Timer creation and will it survive further calls of Reset.

I realize there was change in Go 1.23 with regard to GC-ing timers, but in this case, reference to the timer itself and its channel is held by the program so it is not garbage collected.

cheers,
Wojciech

 

Amnon

unread,
Jun 9, 2026, 6:05:38 PM (2 days ago) Jun 9
to golang-nuts
yes, Timer.C does not get invalidated on Reset.
You can store it as will, read from it, wait for it, and it will survive calls to Reset.

To test it, try something like this:

https://go.dev/play/p/PRDU0sg_uJ-?v=

package main

import (
"fmt"
"time"
)

func main() {
start := time.Now()
delay := time.Second
t := time.NewTimer(delay)
defer t.Stop()

for range t.C {
fmt.Println(time.Since(start))
delay *= 2
t.Reset(delay)
if delay > 16*time.Second {
return
}
}
}
Reply all
Reply to author
Forward
0 new messages