Is there a way to do repetitive tasks at intervals?

后端 未结 7 2050
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 04:42

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

7条回答
  •  时光说笑
    2020-12-04 05:42

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

提交回复
热议问题