Is there a way to do repetitive tasks at intervals?

后端 未结 7 2047
被撕碎了的回忆
被撕碎了的回忆 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:21

    If you want to stop it in any moment ticker

    ticker := time.NewTicker(500 * time.Millisecond)
    go func() {
        for range ticker.C {
            fmt.Println("Tick")
        }
    }()
    time.Sleep(1600 * time.Millisecond)
    ticker.Stop()
    

    If you do not want to stop it tick:

    tick := time.Tick(500 * time.Millisecond)
    for range tick {
        fmt.Println("Tick")
    }
    

提交回复
热议问题