Running multiple methods periodically

Issue

I’m new to go and trying to make two methods run at the same time periodically for as long at the application is running. I’ve managed to come up with the following but the for true part does not feel right as this is blocking.

Would channels be a better way todo this? Any pointers in the right direction would be helpful.

func main() {
    t1 := schedule(ping, time.Second)
    t2 := schedule(ping, 2*time.Second)
    for true {
        time.Sleep(1 * time.Second)
    }
    t1.Stop()
    t2.Stop()
}

func schedule(f func(interval time.Duration), interval time.Duration) *time.Ticker {
    ticker := time.NewTicker(interval)
    go func() {
        for range ticker.C {
            f(interval)
        }
    }()
    return ticker
}

func ping(interval time.Duration) {
    log.Println("ping ", interval)
}

Solution

To prevent the application from exiting, the main goroutine must block.

Use select {} to block the main goroutine.

Because the tickers run for the duration of the application, there’s no need to stop the tickers.

func main() {
    schedule(ping, time.Second)
    schedule(ping, 2*time.Second)
    select {}
}

Answered By – Bayta Darell

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.