Stopping a ticker

What I’m going to ask about is time.Ticker Stop method behavior and more explicitly about the fact that it does not close the channel. The comment in the time package says:

Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

But I cannot make any sense of this. What does it mean?

Also this (not closing the channel) would make the code below not behave as expected.

package main

import (
	"time"
)

func main() {
	ticker := time.NewTicker(time.Millisecond * 500)
	go func() {
		defer func() {
			println("Defered")
		}()
		for t := range ticker.C {
			println(t.String())
		}
		println("Done")
	}()

	time.Sleep(time.Millisecond * 1700)
	ticker.Stop()
	time.Sleep(time.Millisecond * 1700)
}

Any ideas/explanations to enlighten my vision on this?

Code like

for {
  select {
    case cmd := <-commands:
      handle(cmd)
    case <-ticker.C:
      handleTick()
  }
}

would start looping tightly on the ticker branch of the select if it was closed. In your example, you’d probably want to use a select on the ticker.C and a separate stop channel.

But the select would choose randomly between the stop channel and ticker.C wouldn’t it?

If both are readable, yes. So you might get one last run on the ticker branch, before taking the stop branch the next time, if a tick arrives at the same time as the stop.

Very well. Thank you.

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