没有办法Go 执行重复的后台任务?我在想类似的事情Timer.schedule(task,delay,period)Java我知道我可以用 goroutine and 做到这一点Time.sleep(),但我想要一些很容易停止的东西。9 p: u0 }0 R2 g% @% Z& n
这是我得到的,但对我来说看起来很丑。有没有更干净/更好的方法? / U) w. `8 u" u2 F# \3 l1 ]
func oneWay() var f func() var t *time.Timer f = func () fmt.Println("doing stuff") t = time.AfterFunc(time.Duration(5) * time.Second,f) } t = time.AfterFunc(time.Duration(5) * time.Second,f) defer t.Stop() //simulate doing stuff time.Sleep(time.Minute)} ; e; V1 g* C' [# x: g
, L$ X& b2 `- G+ Y; T解决方案: ! F) U; z" _3 T u( C7 Z% i% e 该函数time.NewTicker创建一个发送周期性消息的渠道,并提供一种停止它的方法。这样使用它(未经测试): . |& i$ G. ?. \. l1 T) N) q[code]ticker := time.NewTicker(5 * time.Second)quit := make(chan struct{})go func() for select case 您可以关闭并停止工作器quit通道:close(quit)。