Timer.Reset and channel lifetime

159 views
Skip to first unread message

Wojciech Kaczmarek

unread,
Jun 9, 2026, 1:08:07 PMJun 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 PMJun 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
}
}
}

Wojciech Kaczmarek

unread,
Jun 12, 2026, 1:33:55 PM (13 days ago) Jun 12
to golang-nuts

Thank you Amnon.

I was using similar tests, but I had suspicion I just might be lucky to not hit an underneath channel change.
OTOH, quick look at the runtime/time.go source seems to confirm the channel stays.
Reply all
Reply to author
Forward
0 new messages