go ticker

tags: learning go programming

content

  • a time.Ticker in go provides a channel.
  • when a ticker is created, some internal goroutine is sending value to that channel with the given interval, and the thread which created the channel is receiving values from that channel.
  • the Ticker channel is buffered with buffer size 1
  • when ticker goroutine hasn’t written into the channel, there’s nothing in the channel, hence the reader of the channel is getting blocked

a simple ticker:

func ticker(interval time.Duration) <-chan bool { // return read-only channel
	blocked := make(chan bool, 1)
	go func() {
		for {
			time.Sleep(interval)
			blocked <- true
		}
	}()
	return blocked
}
  • ticker writes into channel every interval, outside func waits for the channel to have content to do something

    • channel empty: outside func gets blocked, or do other stuff
  • the ticker channel has a buffer of 1

  • if channel reader didn’t consume channel content fast enough, ticker would get blocked after time.Sleep() and before blocked<- true

    • because ticker can’t write to channel
  • therefore, the next write to channel will be instant, the waiting has been done

up

go-routine-basics

down

reference