在第一次间隔之前优雅地运行Ticker的身体?

问题描述 投票:2回答:1

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-loop go timer
1个回答
5
投票

我过去这样做过:

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

© www.soinside.com 2019 - 2024. All rights reserved.