Ste*_*fan 30 ruby ruby-on-rails background-process
当创建一个新的资源,它需要做一些冗长的处理前的资源准备好了,我怎么发送处理掉到背景的地方也不会撑起当前请求或其他流量到我的web应用程序?
在我的模型中:
class User < ActiveRecord::Base
after_save :background_check
protected
def background_check
# check through a list of 10000000000001 mil different
# databases that takes approx one hour :)
if( check_for_record_in_www( self.username ) )
# code that is run after the 1 hour process is finished.
user.update_attribute( :has_record )
end
end
end
Run Code Online (Sandbox Code Playgroud)
ujh*_*ujh 40
你一定要查看以下Railscast:
他们解释了如何以各种可能的方式在Rails中运行后台进程(有或没有队列......)
我刚刚尝试了'delayed_job'宝石,因为它可以与Heroku托管平台一起使用,设置起来非常简单!
添加宝石的Gemfile, ,,bundle install
然后开始一个队列处理程序;rails g delayed_job
rake db:migrate
RAILS_ENV=production script/delayed_job start
Run Code Online (Sandbox Code Playgroud)
你有一个方法调用,这是你漫长的过程,即
company.send_mail_to_all_users
Run Code Online (Sandbox Code Playgroud)
你把它改成了;
company.delay.send_mail_to_all_users
Run Code Online (Sandbox Code Playgroud)
检查github上的完整文档:https://github.com/collectiveidea/delayed_job