我编写了一些代码,每30分钟并发轮询url:
func (obj * MyObj) Poll() {
for ;; {
for _, url := range obj.UrlList {
//Download the current contents of the URL and do something with it
}
time.Sleep(30 * time.Minute)
}
//Start the routine in another function
go obj.Poll()
如何添加到obj。并确保下次轮询URL时,轮询程序中的UrlList也已更新,因此也将轮询新的URL?
我知道内存是通过通信共享的,而不是相反,在Go中,我已经研究了通道,但我不确定如何在这个例子中实现它们。
这是一个未经测试但安全的模型,用于定期获取一些url,并能够安全地动态地向url列表中添加新url。如果你想删除一个URL,读者应该很清楚需要做什么。
type harvester struct {
ticker *time.Ticker // periodic ticker
add chan string // new URL channel
urls []string // current URLs
}
func newHarvester() *harvester {
rv := &harvester{
ticker: time.NewTicker(time.Minute * 30),
add: make(chan string),
}
go rv.run()
return rv
}
func (h *harvester) run() {
for {
select {
case <-h.ticker.C:
// When the ticker fires, it's time to harvest
for _, u := range h.urls {
harvest(u)
}
case u := <-h.add:
// At any time (other than when we're harvesting),
// we can process a request to add a new URL
h.urls = append(h.urls, u)
}
}
}
func (h *harvester) AddURL(u string) {
// Adding a new URL is as simple as tossing it onto a channel.
h.add <- u
}
如果您需要定期轮询,则不应该使用time.Sleep
,而应该使用time.Ticker
(或相对于time.After
)。原因是睡眠只是睡眠,并没有考虑到由于你在循环中所做的实际工作而产生的漂移。相反,Ticker有一个单独的程序和一个通道,它们一起能够向您发送常规事件,从而导致一些有用的事情发生。
这里有一个和你的相似的例子。我放了一个随机抖动来说明使用Ticker的好处。
package main
import (
"fmt"
"time"
"math/rand"
)
func Poll() {
r := rand.New(rand.NewSource(99))
c := time.Tick(10 * time.Second)
for _ = range c {
//Download the current contents of the URL and do something with it
fmt.Printf("Grab at %sn", time.Now())
// add a bit of jitter
jitter := time.Duration(r.Int31n(5000)) * time.Millisecond
time.Sleep(jitter)
}
}
func main() {
//go obj.Poll()
Poll()
}
当我运行这个程序时,我发现尽管有抖动,它仍然保持一个严格的10秒周期。
// Type with queue through a channel.
type MyType struct {
queue chan []*net.URL
}
func (t *MyType) poll() {
for urls := range t.queue {
...
time.Sleep(30 * time.Minute)
}
}
// Create instance with buffered queue.
t := MyType{make(chan []*net.URL, 25)}
go t.Poll()