HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoModerate

Executing periodic tasks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
periodicexecutingtasks

Problem

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
}

Solution

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)
    }
}

Code Snippets

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

Context

StackExchange Code Review Q#116066, answer score: 10

Revisions (0)

No revisions yet.