我已经写了一些代码,可以每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.UrlList,并确保下次轮询URL时,轮询goroutine中的UrlList也会更新,这样也会轮询新的URL?
我知道在Go中,内存是通过通信共享的,而不是相反,我已经研究了通道,但我不确定如何在这个例子中实现它们。
发布于 2013-06-04 15:58:20
这是一个未经测试但安全的模型,用于定期获取一些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
}发布于 2013-06-05 04:43:20
如果您需要定期轮询,则不应使用time.Sleep,而应使用time.Ticker (或time.After之类的相对对象)。原因是睡眠只是一种睡眠,并不考虑由于您在循环中所做的实际工作而产生的漂移。相反,Ticker有一个单独的goroutine和一个通道,它们一起能够向您发送常规事件,从而导致一些有用的事情发生。
这里有一个与您的类似的示例。我放了一个随机抖动来说明使用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 %s\n", 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秒的周期,尽管有抖动。
发布于 2013-06-04 02:37:28
// 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()https://stackoverflow.com/questions/16903348
复制相似问题