Timer and ticker in golang

We often want to execute Go code at some point in the future, or repeatedly at some interval. Go’s built-in timerand ticker features make both of these tasks easy

Timer

Timers represent a single event in the future. You tell the timer how long you want to wait, and it provides a channel that will be notified at that time.

The <-timer1.C blocks on the timer’s channel C. This timer will wait 2 seconds until it sends a value indicating that the timer expired.

package main
import "time"
import "fmt"

func main() {
    timer1 := time.NewTimer(5 * time.Second)
    <-timer1.C
    fmt.Println("Timer 1 expired")
}

If you just wanted to wait, you could have usedtime.Sleep. One reason a timer may be useful is that you can cancel the timer before it expires. Here’s an example of that.

timer1 should be stopped before it has a chance to expire.

package main
import "time"
import "fmt"

func main() {
    timer1 := time.NewTimer(5 * time.Second)
    go func() {
        <-timer1.C
        fmt.Println("Timer 1 expired")
    }()
    stop1 := timer1.Stop()
    if stop1 {
        fmt.Println("Timer 1 stopped")
    }
}

Ticker

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.

In this example, I want to create a ticker for repeating every 1 second and print out time of your PC.

By using goroutine, this repeating is processing in other thread. And with sleeping 10 second for main thread. Ticker repeat in 10 second for 10 printing, and stop after 10nth second

package main

import "time"
import "fmt"

func main() {

    ticker := time.NewTicker(1 * time.Second)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()

    time.Sleep(10 * time.Second)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

View on github

PreNext