26. Go - Timers and Tickers

Times are like channels.

Timer execute once in the future.



variable := time.NewTimer(2*time.Second) // creates a new timer


< - variable.C // timer's channel. any code under timer will run when timer runs out.


variable.Stop() // stops a timer


Tickers execute once every interval.


Example:

package main


import (

    "fmt"

    "time"

)


func main() {


    ticker := time.NewTicker(500 * time.Millisecond) // creates a ticker

    done := make(chan bool) // creates a channel that takes bool


    go func() {

        for { // infinite loop

            select {

            case <-done: // if done chan receive true bool, then return

                return

            case t := <-ticker.C: // if ticker chan gets a tick, then print

                fmt.Println("Tick at", t)

            }

        }

    }()


    time.Sleep(1600 * time.Millisecond) // stops program at 1600 millisecond

    ticker.Stop() // stops ticker

    done <- true // send done chan a true bool

    fmt.Println("Ticker stopped")

}

Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort