美文网首页
Go 定时任务

Go 定时任务

作者: ShootHzj | 来源:发表于2022-02-24 17:32 被阅读0次

    不使用三方库

    协程Sleep方式

    go func() {
        for true {
            fmt.Println("Hello !!")
            time.Sleep(1 * time.Second)
        }
    }()
    

    使用ticker方式1

    ticker := time.NewTicker(1 * time.Second)
    go func() {
        for range ticker.C {
            fmt.Println("Hello !!")
        }
    }()
    
    // wait for 10 seconds
    time.Sleep(10 *time.Second)
    ticker.Stop()
    

    使用ticker方式2

    done := make(chan bool)
    ticker := time.NewTicker(1 * time.Second)
    
    go func() {
        for {
            select {
            case <-done:
                ticker.Stop()
                return
            case <-ticker.C:
                fmt.Println("Hello !!")
            }
        }
    }()
    
    // wait for 10 seconds
    time.Sleep(10 *time.Second)
    done <- true
    

    参考

    https://stackoverflow.com/questions/53057237/how-to-schedule-a-task-at-go-periodically

    相关文章

      网友评论

          本文标题:Go 定时任务

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