Tickers

time.Ticker is similar to time.Timer, but its channel delivers more elements at regular intervals equal to the duration. They are specified when creating it with time.NewTicker.  This makes it possible to stop the ticker from firing with the Ticker.Stop method:

func main() {
tick := time.NewTicker(time.Millisecond)
stop := time.NewTimer(time.Millisecond * 10)
for {
select {
case a := <-tick.C:
fmt.Println(a)
case <-stop.C:
tick.Stop()
case <-time.After(time.Millisecond):
return
}
}
}

The full example is available at https://play.golang.org/p/8w8I7zIGe-_j.

In this example, we are also using time.After—a function that returns the channel from an anonymous time.Timer. This can be used when there's no need to stop the timer. There is another functiontime.Tick, that returns the channel of an anonymous time.Ticker. Both functions will return a channel that the application has no control over and this channel will eventually be picked up by the garbage collector.

This concludes the overview of channels, from their properties and basic usage to some more advanced concurrency examples. We also checked some special cases and how to synchronize multiple channels.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181