The right way to restart time.Timer

Hello! I am using time.Timer in my code. There is one goroutine which is waiting for the Timer to expire. I have another goroutine which wants to restart the above timer under certain conditions. When the timer is restarted, the timer may or may not be expired yet. The first goroutine (which is waiting for the timer to expire), also restarts the timer on expiration. What is the effective way to do this, without any race conditions or deadlocks?

BTW, I did try the method explained in the docs:

if !t.Stop() {
    <-t.C
}
t.Reset(d)

But I’ve observed line 2 (draining out the channel) blocking in some cases.

Thanks

I’ve also posted the question on the golang subreddit: https://www.reddit.com/r/golang/comments/f16kqy/the_right_way_to_restart_timetimer/

The return from Stop() just says if the timer had expired, not whether someone else has already read from the channel or not. In your case you can’t be sure if the other routine has already done so or not. I would try a nonblocking read;

t.Stop()
select {
  case <-t.C:
  default:
}
t.Reset(d)
1 Like

Thanks that works

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.