Channels, Timeouts, and Tickers
Explore Go's concurrency features by learning to use channels with timeouts and tickers. Understand how to control goroutine execution, implement rate limiting, handle time-based events, and manage asynchronous operations effectively.
We'll cover the following...
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
...
}
...