【问题标题】:Rails Rake task displayed execution expired message and program stoppedRails Rake 任务显示执行过期消息和程序停止
【发布时间】:2011-06-10 09:39:00
【问题描述】:

我有一个使用回形针从表格网站加载汽车图像的 rake 任务。图像作为远程链接存储在数据库中。

这是我的代码,我使用的是 ruby​​ 1.8.7、rails 2.3.8 和 DB mysql。

namespace :db do

  task :load_photo  => :environment do
  require 'rubygems'
  require 'open-uri'
  require 'net/http'
  require 'paperclip'
  begin
  images =Website.find(:all,:conditions=>["image_url is not null"])
  images.each do |photo|
     url = URI.parse(photo.image_url)
     Net::HTTP.start(url.host, url.port) do |http|
         if http.head(url.request_uri).code == "200"
           Car.update_attribute(:photo,open(url))
         end
     end
  end
  rescue Exception => e
  end
 end 
 end 

通过 db:load_photo 运行上述 rake 任务。在我的表(网站)中有 60,000 行。仅运行最多 10000 行的 Rake 任务,执行终止并显示错误消息 “执行已过期”

谁能帮我解决这个问题?

提前致谢。

【问题讨论】:

标签: ruby-on-rails rake paperclip


【解决方案1】:

您可能会发现批量运行它的性能更高,活动记录有一个find_in_batches 方法,可以停止一次将所有记录加载到内存中。

http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find

您可以将代码更改为:

namespace :db do
  task :load_photo  => :environment do
    require 'rubygems'
    require 'open-uri'
    require 'net/http'
    require 'paperclip'
    Website.find_in_batches(:conditions=>["image_url is not null"]) do |websites|
      websites.each do |website|
        begin
          url = URI.parse(website.image_url)
          Net::HTTP.start(url.host, url.port) do |http|
            if http.head(url.request_uri).code == "200"
              Car.update_attribute(:photo,open(url))
            end
          end
        rescue Exception => e
        end
      end
    end
  end 
end

【讨论】:

  • 嗨,安德鲁,你能帮我解决 rake 中止的问题吗!#<0x4df19d8>
【解决方案2】:

我只能猜测,但看起来您正在对要从中提取图像的服务器进行小型 DoS 攻击。

您可以尝试在连续请求之间稍稍延迟播放(例如“sleep 1”)。

另外,如果你的“执行过期”是一个 Timeout::Error 异常,那么你不能用

rescue Exception => e

因为 Timeout::Error 不是 StandardError 的子类,它是 Interrupt 类的子类。你必须明确地抓住它,像这样:

rescue Timeout::Error => e

【讨论】:

  • 嗨,Alexis,我也尝试过 Timeout::Error 异常处理,但仍然 rake 任务过期或显示 SIGNUP 消息。帮帮我谢谢!
  • 你也可以尝试不带参数的“rescue”——这将捕获任何类型的异常。另外,在终止之前是否总是正好 10000 行?
  • 您是否尝试在每次请求后添加延迟?我仍然认为问题是服务器因您的请求而过载。如果每个请求后的“睡眠 1”太慢,您可以将其与 Andrew Nesbitt 的“find_in_batches”建议结合使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
相关资源
最近更新 更多