没有办法Go 执行重复的后台任务?我在想类似的事情Timer.schedule(task,delay,period)Java我知道我可以用 goroutine and 做到这一点Time.sleep(),但我想要一些很容易停止的东西。 K; g- n! H+ X
这是我得到的,但对我来说看起来很丑。有没有更干净/更好的方法? 9 q" r8 {( g6 Q1 o4 p
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)}) x6 b3 q' y: P+ B) f
( ]& z J5 q$ Y+ o 解决方案: 5 d& F- K8 U/ j8 j+ J6 {+ X' c7 w5 D
该函数time.NewTicker创建一个发送周期性消息的渠道,并提供一种停止它的方法。这样使用它(未经测试):4 H' o8 x3 `+ o
[code]ticker := time.NewTicker(5 * time.Second)quit := make(chan struct{})go func() for select case 您可以关闭并停止工作器quit通道:close(quit)。