Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Go by Example: Tickers

Timers are for when you want to do something once


in the future - tickers are for when you want to do
something repeatedly at regular intervals. Here’s an
example of a ticker that ticks periodically until we
stop it.

package main

import (
"fmt"
"time"
)

func main() {

Tickers use a similar mechanism to timers: a channel ticker := time.NewTicker(500 * time.Millisecond)


that is sent values. Here we’ll use the select builtin on done := make(chan bool)
the channel to await the values as they arrive every
500ms.

go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()

Tickers can be stopped like timers. Once a ticker is time.Sleep(1600 * time.Millisecond)


stopped it won’t receive any more values on its ticker.Stop()
channel. We’ll stop ours after 1600ms. done <- true
fmt.Println("Ticker stopped")
}

When we run this program the ticker should tick 3 $ go run tickers.go
times before we stop it. Tick at 2012-09-23 11:29:56.487625 -0700 PDT
Tick at 2012-09-23 11:29:56.988063 -0700 PDT
Tick at 2012-09-23 11:29:57.488076 -0700 PDT
Ticker stopped

Next example: Worker Pools.

by Mark McGranaghan and Eli Bendersky | source | license

You might also like