运行 定期使用多种方法

Running multiple methods periodically

我是新手,尝试同时定期制作两种方法 运行,只要应用程序是 运行ning。我设法想出了以下内容,但 for true 部分感觉不对,因为这是阻塞的。

渠道会是更好的方式吗?任何正确方向的指示都会有所帮助。

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

要防止应用程序退出,主 goroutine 必须阻塞。

使用select {}阻塞主goroutine。

因为在申请期间的行情运行,所以没有必要停止行情。

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