2011-08-23 32 views
2

我已經建立了其投給我上的網站代碼...紅寶石/機械化任何方式來消耗RAM? - >無法分配內存

的Ruby腳本工作得很好,但少數分鐘再予這個腳本停止這一錯誤後:link of the screen-shot

所以我檢查了Windows任務管理器和ruby.exe的內存分配到每個循環之後!

這裏是代碼證其罪和平:

class VoteWebsite 
     def self.main 
     agent = Mechanize.new 
     agent.user_agent_alias = 'Windows Mozilla' 
    while $stop!=true 
     page = agent.get 'http://website.com/vote.php' 
     reports_divs = page.search(".//div[@class='Pad1Color2']") 
     tds = reports_divs.search("td") 
     i = 3;j = 0;ouiboucle=0;voteboucle=0 
     while i < tds.length 
      result = tds[i].to_s.scan(/<font class="ColorRed"><b>(.*?) :<\/b><\/font>/) 
      type = result[0].to_s[2..-3] 
      k=i 
      case type 
      when "Type of vote" 
       j= i+1;i += 4 
       result2 = tds[j].to_s.scan(/<div id="btn(.*?)">/)   
       id = result2[0].to_s[2..-3] 
       monvote=define_vote($vote_type, tds[k].to_s, $vote_auto) 
       page2 = agent.get 'http://website.com/AJAX_Vote.php?id='+id+'&vote='+monvote 
       voteboucle+=1 
       . 
       . 
       . 
      else 
       . 
       . 
       . 
      end 
     end  
    end 
    end 
end 
VoteWebsite.main 

我想聲明的方法全局變量裏面所有的變量都應該解決這個問題probleme但代碼是相當大的和有變數普朗蒂內這種方法。

所以有任何方法(任何Ruby指令)在每次循環結束時排出所有此變量?

回答

2

問題出現了,實際上,從機械化的歷史see this answerMechanize::History.clear方法或甚至只是將Mechanize::History.max_size屬性設置爲合理的值。

#!/usr/bin/env ruby 

require 'mechanize' 

class GetContent 
    def initialize url 
     agent = Mechanize.new 
    agent.user_agent_alias = 'Windows Mozilla' 
    agent.history.max_size=0 
    while true 
      page = agent.get url 
     end 
    end 
end 

myPage = GetContent.new('http://www.nypost.com/') 

希望它有幫助!

1

你總是可以強制垃圾收集踢:

GC.start 

作爲一個說明,這看起來不是很紅寶石。到使用;一行包裝多條語句是壞的形式,並使用$類型變量大概是從別的東西被移植的遺物。

記住$ -prefixed變量在Ruby中全局變量,如果不小心使用,並應保留非常特殊的情況下可能會導致噸的問題。最好的選擇是@ -prefixed實例變量,或者如果必須,一個宣稱CONSTANT

+1

非常感謝我會盡快托盤... 我知道我的紅寶石編程非常髒。你不是第一個告訴我的。 非常感謝這個有用的幫助 – cz3ch