7
\$\begingroup\$

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
    <-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 <- ticker.C:
                //Call the periodic function here.
                periodicFunc(<- ticker.C)
            }
        }
     }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    <-quit
}
\$\endgroup\$
10
\$\begingroup\$

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)
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ So, how do you quit from this loop? You need a select inside the loop again, right? \$\endgroup\$ Aug 12 '17 at 12:37
  • \$\begingroup\$ Take a look at stackoverflow.com/a/16466561/4196282; it shows how to use the channel that a Ticker contains. \$\endgroup\$
    – Jim Nasby
    Oct 12 '17 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.