drls2738 2013-05-09 16:13
浏览 45
已采纳

有没有办法定期执行重复性任务?

Is there a way to do repetitive background tasks in Go? I'm thinking of something like Timer.schedule(task, delay, period) in Java. I know I can do this with a goroutine and Time.sleep(), but I'd like something that easily stopped.

Here's what I got, but looks ugly to me. Is there a cleaner/better way?

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)
}
  • 写回答

7条回答 默认 最新

  • douhai5835 2013-05-09 16:28
    关注

    The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):

    ticker := time.NewTicker(5 * time.Second)
    quit := make(chan struct{})
    go func() {
        for {
           select {
            case <- ticker.C:
                // do stuff
            case <- quit:
                ticker.Stop()
                return
            }
        }
     }()
    

    You can stop the worker by closing the quit channel: close(quit).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog