Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simple Golang Ticker Example Using Go Subroutine

We will create Ticker example using time package.I will create channel and wait 4 second to execute main channel, That 4 second wait time will use to show 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 task 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 package into main.go file:

package main

import (
	"fmt"
	"time"
)

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

We will defined main method into 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
	ticker.Stop()
}

We have created NewTicker() method using using NewTicker().The next line call ticker using go subroutine.We will sleep execution of main goroutine for 4 sec, The sleep time help 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.

The post Simple Golang Ticker Example Using Go Subroutine appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

Simple Golang Ticker Example Using Go Subroutine

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×