Executing periodic tasks I am writing a code in Golang to execute a periodic function (every 2 second). According to documentation and an example I have written two programs. Can anybody tell which one is better? Also, is there another better solution?

Code 1:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}

func main(){
    fmt.Println("Starting a new ticker....")

    ticker := time.NewTicker(2 * time.Second)
    go func(){
        for t := range ticker.C {
            //Call the periodic function here.
            periodicFunc(t)
        }
    }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    &lt;-quit
}


Code 2:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}
func main(){
    ticker := time.NewTicker(1 * time.Second)

    go func() {
        for {
           select {
            case &lt;- ticker.C:
                //Call the periodic function here.
                periodicFunc(&lt;- ticker.C)
            }
        }
     }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    &lt;-quit
}
A vs. B type questions are seldom good questions for a code review. Often the answer is "C".

That's true this time too.


You don't need a go routine for the "ticker".
Your second implementation only waits for 1 second, instead of 2.
your "quit" channels don't need to be buffered


Why don't you just do:

func main() {
    for t := range time.NewTicker(2 * time.Second).C {
        periodicFunction(t)
    }
}