dongqiongjiong4740 2015-09-21 22:35 采纳率: 0%
浏览 62

如何获取时间。

I have a loop that iterates until a job is up and running:

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")
    }
}

Works great in production. The only problem is that it makes my tests slow. They all wait at least 2 seconds before completing. Is there anyway to get time.Tick to tick immediately?

  • 写回答

4条回答 默认 最新

  • dsfsdfsdfsdfsdf45454 2015-09-22 02:13
    关注

    The actual implementation of Ticker internally is pretty complicated. But you can wrap it with a goroutine:

    func NewTicker(delay, repeat time.Duration) *time.Ticker {
        ticker := time.NewTicker(repeat)
        oc := ticker.C
        nc := make(chan time.Time, 1)
        go func() {
            nc <- time.Now()
            for tm := range oc {
                nc <- tm
            }
        }()
        ticker.C = nc
        return ticker
    }
    
    评论

报告相同问题?