dqch34769 2013-06-03 18:25
浏览 135
已采纳

Go中的预定轮询任务

I have written some code that will concurrently poll URLs every 30 minutes:

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()

How would I then add to obj.UrlList elsewhere in the code and ensure that the next time the URLs are polled that the UrlList in the Poll goroutine as also been updated and as such will also poll the new URL?

I understand that memory is shared through communicating rather than vice versa in Go and I've investigated channels however I'm not sure how to implement them in this example.

  • 写回答

3条回答 默认 最新

  • doujing9972 2013-06-04 07:58
    关注

    Here's an untested, but safe model for periodically fetching some URLs with the ability to dynamically add new URLs to the list of URLs safely. It should be obvious to the reader what would be required if you wanted to remove a URL as well.

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。