猿问

如何获得 time.Tick 立即打勾

我有一个循环,直到工作启动并运行:


ticker := time.NewTicker(time.Second * 2)

defer ticker.Stop()


started := time.Now()

for now := range ticker.C {

    job, err := client.Job(jobID)

    switch err.(type) {

    case DoesNotExistError:

        continue

    case InternalError:

        return err

    }


    if job.State == "running" {

        break

    }


    if now.Sub(started) > time.Minute*2 {

        return fmt.Errorf("timed out waiting for job")

    }

}

在生产中效果很好。唯一的问题是它使我的测试变慢。他们都至少等待 2 秒钟才能完成。有没有time.Tick办法立即打勾?


函数式编程
浏览 154回答 3
3回答

UYOU

不幸的是,Go 开发人员似乎不会在任何可预见的未来添加这样的功能,所以我们必须应对......有两种常用的代码使用方法:for 环形鉴于这样的事情:ticker := time.NewTicker(period)defer ticker.Stop()for <- ticker.C {&nbsp; &nbsp; ...}用:ticker := time.NewTicker(period)defer ticker.Stop()for ; true; <- ticker.C {&nbsp; &nbsp; ...}for-select循环鉴于这样的事情:interrupt := make(chan os.Signal, 1)signal.Notify(interrupt, os.Interrupt)ticker := time.NewTicker(period)defer ticker.Stop()loop:for {&nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <- ticker.C:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f()&nbsp; &nbsp; &nbsp; &nbsp; case <- interrupt:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break loop&nbsp; &nbsp; }}用:interrupt := make(chan os.Signal, 1)signal.Notify(interrupt, os.Interrupt)ticker := time.NewTicker(period)defer ticker.Stop()loop:for {&nbsp; &nbsp; f()&nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <- ticker.C:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; case <- interrupt:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break loop&nbsp; &nbsp; }}为什么不直接使用time.Tick()?尽管 Tick 对于不需要关闭 Ticker 的客户端很有用,但请注意,如果无法关闭它,则垃圾收集器无法恢复底层的 Ticker;它“泄漏”。https://golang.org/pkg/time/#Tick

千万里不及你

ticker := time.NewTicker(period)for ; true; <-ticker.C {&nbsp; &nbsp; ...}https://github.com/golang/go/issues/17601

慕村225694

Ticker内部的实际实现是相当复杂的。但是你可以用一个 goroutine 包装它:func NewTicker(delay, repeat time.Duration) *time.Ticker {&nbsp; &nbsp; ticker := time.NewTicker(repeat)&nbsp; &nbsp; oc := ticker.C&nbsp; &nbsp; nc := make(chan time.Time, 1)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; nc <- time.Now()&nbsp; &nbsp; &nbsp; &nbsp; for tm := range oc {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nc <- tm&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; ticker.C = nc&nbsp; &nbsp; return ticker}
随时随地看视频慕课网APP

相关分类

Go
我要回答