Simple Golang Ticker Example Using Go Subroutine

Simple Golang Ticker Example Using Go Subroutine

We will create a ticker example using a time package. I will create a channel and wait 4 seconds to execute the main channel, That 4 second wait time will use to show the ticker countdown.

We will use Goroutines method, The Goroutine is a lightweight thread of execution.

Go Has inbuilt times and ticker features with time package, The Timers is used to run tasks once in the future whereas Ticker is used to run task repeatedly at regular intervals.

You tell the timer how long you want to wait, and it provides a channel that will be notified at that time.

The Times and Tickers both can be stopped using stop() method, They won’t receive any more values on its channel.

Go Tickers Example Using Goroutine

We will import the package into main.go file:

package main

import (

We have created the main package and import packages fmt for print data and time for tickers.

We will define the main method in main.go file.

func main() {
        fmt.Println("Hey! wait 4 sec---")
        //create ticker
        ticker := time.NewTicker(time.Second * 1)
        //call channe;
        go ticker_clock(ticker)
        //sleep 4 sec
        time.Sleep(4 * time.Second)
        //stope ticker

We have created NewTicker() method using using NewTicker().The next line call ticker using go subroutine.

We will sleep execution of the main goroutine for 4 sec, The sleep time helps to execute ticker_clock() Goroutines method.

func ticker_clock(ticker *time.Ticker) {
        i := 1
        for t := range ticker.C {
                fmt.Println("Tick at", i)
                fmt.Println("Tick at", t)
                i = i + 1

We will create ticker_clock() method that takes ticker type variable.

One Reply to “Simple Golang Ticker Example Using Go Subroutine”

  1. I need to thank you for this good article!!

Comments are closed.