Go by Example: Tickers

A ticker is a special type of timer that repeatedly sends a value on a channel at regular intervals. Here’s an example:

package main

import "time"
import "fmt"

func main() {
  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)
      }
    }
  }()

  time.Sleep(1600 * time.Millisecond)
  ticker.Stop()
  done <- true
  fmt.Println("Ticker stopped")
}

In this example, we create a ticker that sends a value on ticker.C channel every 500 milliseconds. The channel is read by a goroutine which repeatedly selects the value sent on it. After sleeping for 1600 milliseconds, the main function stops the ticker and sends a signal to the goroutine to exit.

A ticker is a special type of timer that repeatedly fires an event at regular intervals. In Go, a ticker is implemented using the time.Ticker type, which can be created using time.NewTicker function. The time.Ticker type provides a simple way to regularly perform a task, for example, printing a message every second. Here’s an example:

package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	done := make(chan bool)

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

	time.Sleep(5 * time.Second)
	ticker.Stop()
	done <- true
	fmt.Println("Ticker stopped")
}

The output of this program will be:

Tick at 2022-11-19 19:55:41.0724534 +0530 IST
Tick at 2022-11-19 19:55:42.0726159 +0530 IST
Tick at 2022-11-19 19:55:43.072797 +0530 IST
Tick at 2022-11-19 19:55:44.0729734 +0530 IST
Tick at 2022-11-19 19:55:45.0731699 +0530 IST
Ticker stopped
Done

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *