Is there a way to do repetitive tasks at intervals?

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

    How about something like

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func schedule(what func(), delay time.Duration) chan bool {
        stop := make(chan bool)
    
        go func() {
            for {
                what()
                select {
                case <-time.After(delay):
                case <-stop:
                    return
                }
            }
        }()
    
        return stop
    }
    
    func main() {
        ping := func() { fmt.Println("#") }
    
        stop := schedule(ping, 5*time.Millisecond)
        time.Sleep(25 * time.Millisecond)
        stop <- true
        time.Sleep(25 * time.Millisecond)
    
        fmt.Println("Done")
    }
    

    Playground

提交回复
热议问题