How to use Tickers in Golang?

Go ProgrammingServer Side ProgrammingProgramming

There are often cases where we would want to perform a particular task after a specific interval of time repeatedly. In Golang, we achieve this with the help of tickers.

We can use them with goroutines as well so that we can run these tasks in the background of our application without breaking the flow of the application.

The function that we use in tickers is the NewTicker() function which takes time as an argument and we can supply seconds and even milliseconds in it.

Example 1

The following example demonstrates how we can use a ticker in Golang. Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func main() {
   fmt.Println("Starting the ticker")

   ticker := time.NewTicker(1 * time.Second)

   for _ = range ticker.C {
      fmt.Println("Ticking..")
   }
}

Output

If we run the above code with the command go run main.go then we will get the following output.

Starting the ticker
Ticking..
Ticking..

It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C.

Example 2

We can also run the ticker in the background with the help of goroutines. Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func inBackground() {
   ticker := time.NewTicker(1 * time.Second)

   for _ = range ticker.C {
      fmt.Println("Ticking..")
   }
}

func main() {
   fmt.Println("Starting the ticker")
   go inBackground()
   fmt.Println("After goroutine..")
   select {}
}

Output

If we run the above code with the command go run main.go then we will get the following output.

Starting the ticker
After goroutine..
Ticking..
Ticking..

It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C.

Example 3

Now let's consider a more advanced use-case of the ticker, in which we will make use of a channel and a select statement and the ticker will run for a defined period of time as well.

Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func main() {
   ticker := time.NewTicker(400 * time.Millisecond)
   done := make(chan bool)
   fmt.Println("Started!")
   go func() {
      for {
         select {
         case <-done:
            return
         case t := <-ticker.C:
            fmt.Println("Tick at", t)
         }
      }
   }()
   time.Sleep(1600 * time.Millisecond)
   ticker.Stop()
   done <- true
   fmt.Println("Stopped!")
}

Output

If we run the above code with the command go run main.go then we will get the following output.

Started!
Tick at 2009-11-10 23:00:00.4 +0000 UTC m=+0.400000001
Tick at 2009-11-10 23:00:00.8 +0000 UTC m=+0.800000001
Tick at 2009-11-10 23:00:01.2 +0000 UTC m=+1.200000001
Tick at 2009-11-10 23:00:01.6 +0000 UTC m=+1.600000001
Stopped!
raja
Published on 01-Nov-2021 07:28:20

Advertisements