gpt4 book ai didi

go - 如何获得时间。滴答立即滴答

转载 作者:IT王子 更新时间:2023-10-29 00:49:15 25 4
gpt4 key购买 nike

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

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 立即打勾?

最佳答案

不幸的是,它seems Go 开发人员在任何可预见的 future 都不会添加此类功能,因此我们必须应对...

有两种常用的代码使用方式:

for 循环

给定这样的东西:

ticker := time.NewTicker(period)
defer ticker.Stop()
for <- ticker.C {
...
}

使用:

ticker := time.NewTicker(period)
defer ticker.Stop()
for ; true; <- ticker.C {
...
}

for-select循环

给定这样的东西:

interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)

ticker := time.NewTicker(period)
defer ticker.Stop()

loop:
for {
select {
case <- ticker.C:
f()
case <- interrupt:
break loop
}
}

使用:

interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)

ticker := time.NewTicker(period)
defer ticker.Stop()

loop:
for {
f()

select {
case <- ticker.C:
continue
case <- interrupt:
break loop
}
}

为什么不直接使用 time.Tick()

While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks".

https://golang.org/pkg/time/#Tick

关于go - 如何获得时间。滴答立即滴答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32705582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com