...

/

Channels, Timeouts, and Tickers

Channels, Timeouts, and Tickers

This lesson explains how to set the responses of goroutines with time as a controlling factor.

The time package has some interesting functionality to use in combination with channels. It contains a struct time.Ticker, which is an object that repeatedly sends a time value on a contained channel C at a specified time interval:

type Ticker struct {
  C <-chan Time // the channel on which the ticks are delivered.
  // contains filtered or unexported fields
  ...
}

A Ticker can be very useful when, during the execution of goroutines, something (logging a status, a printout, a calculation, and so on) has to be done periodically at a certain time interval. It is stopped with Stop(); use this in a defer statement. All this fits nicely in a select statement:

ticker := time.NewTicker(updateInterval)
defer ticker.Stop()
...
select {
  case u:= <- ch1:
    ...
  case v:= <- ch2:
    ...
  case <- ticker.C:

   logState(status) // e.g. call some logging function logState

  default: // no value ready to be received
    ...
}

The time.Tick() function with ...