美文网首页
gocron定时任务

gocron定时任务

作者: 帶頭二哥 | 来源:发表于2019-12-20 01:26 被阅读0次

    安装:

    go get -u github.com/jasonlvhit/gocron
    

    每隔1秒执行一个任务,每隔4秒执行另一个任务:

    package main
    
    import (
        "fmt"
        "time"
    
        "github.com/jasonlvhit/gocron"
    )
    
    func task() {
        fmt.Println("I am runnning task.", time.Now())
    }
    func superWang() {
        fmt.Println("I am runnning superWang.", time.Now())
    }
    
    func main() {
        s := gocron.NewScheduler()
        s.Every(1).Seconds().Do(task)
        s.Every(4).Seconds().Do(superWang)
    
        sc := s.Start() // keep the channel
        go test(s, sc)  // wait
        <-sc            // it will happens if the channel is closed
    }
    
    func test(s *gocron.Scheduler, sc chan bool) {
        time.Sleep(8 * time.Second)
        s.Remove(task) //remove task
        time.Sleep(8 * time.Second)
        s.Clear()
        fmt.Println("All task removed")
        close(sc) // close the channel
    }
    

    相关文章

      网友评论

          本文标题:gocron定时任务

          本文链接:https://www.haomeiwen.com/subject/jecbnctx.html