我刚开始尝试让两种方法在应用程序运行时定期同时运行。我设法想出了以下内容,但 for true
部分感觉不对,因为这是阻塞的。
channel 会是更好的方式吗?任何指向正确方向的指示都会有所帮助。
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 {}
}
关于go - 定期运行多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55768994/