Timers and Tickers

GolangGolangBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab is about using tickers in Golang. Tickers are used when you want to do something repeatedly at regular intervals.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/tickers("`Tickers`") subgraph Lab Skills go/tickers -.-> lab-15520{{"`Timers and Tickers`"}} end

Timers and Tickers

In this lab, you need to create a ticker that ticks every 500ms until we stop it. You will use a channel to await the values as they arrive.

  • Use the time package to create a ticker.
  • Use a channel to await the values as they arrive.
  • Use the select statement to receive values from the channel.
  • Stop the ticker after 1600ms.
## When we run this program the ticker should tick 3 times
## before we stop it.
$ go run tickers.go
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

There is the full code below:

// [Timers](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 that is sent values. Here we'll use the
	// `select` builtin on the channel to await the
	// values as they arrive every 500ms.
	ticker := time.NewTicker(500 * time.Millisecond)
	done := make(chan bool)

	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 stopped it won't receive any more values on its
	// channel. We'll stop ours after 1600ms.
	time.Sleep(1600 * time.Millisecond)
	ticker.Stop()
	done <- true
	fmt.Println("Ticker stopped")
}

Summary

In this lab, you learned how to use tickers in Golang. You created a ticker that ticks every 500ms until we stop it, used a channel to await the values as they arrive, and stopped the ticker after 1600ms.

Other Golang Tutorials you may like