I have an idle timeout timer being select
ed on in a goroutine, if I see activity I want to cancel the timer.
I had a look at the documentation and I'm not positive I'm clear on what it says.
func (t *Timer) Stop() bool
Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.To prevent a timer created with NewTimer from firing after a call to Stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:
if !t.Stop() { <-t.C }
This cannot be done concurrent to other receives from the Timer's channel.
I'm trying to understand when I have to drain the channel manually.
I'll list my understanding and if I'm wrong please correct me.
If Stop
returned false
this means either:
- The timer was already stopped
- In this case, reading from the channel will block so I shouldn't do it
- The timer was already expired
- Since I have another goroutine listening on the channel, can I know for certain if it has received the event?
- From the "this cannot be done concurrent to other receives" part of the documentation it appears that this isn't an option, so what should I do?
In my case getting a superfluous event from the timer is no big deal, does that inform what I should do here?