Golang timer function executes a function every few minutes

Delay calling AfterFunc

go function()
 
 
func function() {
	// TODO Specific logic
 
	// executed every 5 minutes, recursively calling itself
	time.AfterFunc(5*time.Minute, function)
}

Tickers

package main

import "time"
import "fmt"

func main() {

    // The mechanism of a punter and a timer is somewhat similar: a channel is used to send data. </span
    // Here we use the built-in `range` on this channel to iterate over the values every
    // The value sent once in 500ms.
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()

    // The punctuator can be stopped in the same way as the timer. </span
    // Once a punctuation is stopped, it will no longer be able to receive values from its channel. 
    // We will stop this punter after 1600ms of running.
    time.Sleep(time.Millisecond * 1600)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

When we run this program, the dotter will do 3 times before we stop it.

go run tickers.go
Tick at 2012-09-23 11:29:56.487625 -0700 PDT
Tick at 2012-09-23 11:29:56.988063 -0700 PDT
Tick at 2012-09-23 11:29:57.488076 -0700 PDT
Ticker stopped

Read More:

Leave a Reply

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