4 ms·
You can also use time.Tickers to schedule events to occur every so often in a similar fashion. for now := range time.NewTicker(time.Minute).C { fmt
by jzelinskie 13y ago
You can also use time.Tickers to schedule events to occur every so often in a similar fashion.
for now := range time.NewTicker(time.Minute).C {
fmt.Printf("%s is the current time\n", now)
}
In case you are unfamiliar, the range keyword, when used on a channel, is equivalent to:
for {
select {
case now := <-time.NewTicker(time.Minute).C:
fmt.Printf("%s is the current time\n", now)
}
}
- zimbatm 13y agoOn the second example, wouldn't it make sense to create the ticker outside of the for loop instead ?
- jzelinskie 13y agoYep, that was my bad. I got distracted when writing the example and didn't think things through because I realized I had installed Go 1.1 for i386 on my laptop and not x86_64. Such is life when commenting at 6AM :P
- ominous_prime 13y agoNo, it operates more like: ticker := time.NewTicker(time.Minute) for { now, ok := <-ticker.C if !ok { break } fmt.Printf("%s is the current time\n", now) } Your two loops are superficially equivalent only because the ticker isn't going to close its channel. Plus, you're creating a new ticker on every iteration in your second example, and you don't need the select statement, because your only blocking on a single receive operation. The range over a channel is especially useful for a channel that will be closed, so you can break from the loop.