gpt4 book ai didi

for-loop - 在第一个间隔之前优雅地运行 Ticker 的主体?

转载 作者:IT王子 更新时间:2023-10-29 01:25:42 26 4
gpt4 key购买 nike

Go 的新手,我实现了一个小的 Ticker以给定的时间间隔轮询 API:

func Poll() <-chan map[uint8]Data {
json := make(chan map[uint8]Data)

user, pass, endpoint := credentials.Get()

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

client := &http.Client{}
req, _ := http.NewRequest("GET", endpoint, nil)
req.SetBasicAuth(user, pass)

go func() {
for range ticker.C {
resp, _ := client.Do(req)
bodyText, _ := ioutil.ReadAll(resp.Body)
json <- extract(string(bodyText))
}
}()

return json
}

很明显,这会等到第一个完整间隔结束后才调用 API 进行第一次轮询;这是不可取的。

这个幼稚(但有效)的解决方案似乎...很奇怪:

go func() {
resp, _ := client.Do(req)
bodyText, _ := ioutil.ReadAll(resp.Body)
json <- extract(string(bodyText))
}()

go func() {
for range ticker.C {
resp, _ := client.Do(req)
bodyText, _ := ioutil.ReadAll(resp.Body)
json <- extract(string(bodyText))
}
}()

是否有更好或更惯用的 Go 方法来完成此任务?

最佳答案

我以前这样做过:

for ; true; <-ticker.C {
resp, _ := client.Do(req)
bodyText, _ := ioutil.ReadAll(resp.Body)
json <- extract(string(bodyText))
}

例如:

t := time.NewTicker(2 * time.Second)
now := time.Now()
for ; true; <-t.C {
fmt.Println(time.Since(now))
}

https://play.golang.org/p/1wz99kzZZ92

关于for-loop - 在第一个间隔之前优雅地运行 Ticker 的主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603377/

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