Golang之wait.Until 简单测试用例

原文链接:https://studygolang.com/articles/13441?fr=sidebar

package main

import (
    "fmt"
    "k8s.io/apimachinery/pkg/util/wait"
    "time"
)

type stop struct {
}

func main() {
    stopCh := make(chan struct{})
    //初始化一个计数器
    i := 0
    go wait.Until(func() {
        fmt.Printf("----%d----\n", i)

        i++
    }, time.Second, stopCh)

    time.Sleep(time.Second * 10)

    stopCh <- stop{}
    // 下面的形式,也是可以的
    //stopCh < struct {
    //}{}

    fmt.Println("---上面的go routines 结束----")

    // 主程序,再休息3秒钟,再结束
    time.Sleep(time.Second * 3)

    fmt.Println("---主程序结束----")
}
就是启动一个协程,每隔一定的时间,就去运行声明的匿名函数,直到接收到结束信号 就关闭这个协程

 

posted @ 2021-09-27 16:37  salami_china  阅读(342)  评论(0编辑  收藏  举报