Rails background process - simple, fast, easy.

My situation was this -

  • Rails 2.0 app running on slicehost (ubuntu 8.04) in passenger mod_rails
  • The goal was Dynamic PDF generation for a product catalog ( > 100 pages)
  • This event had to be triggered from within the rails request / response cycle, but run outside of it
  • I needed the simplest, fastest, more reliable way for this to happen

I looked at BackgroundRB, it is the most robust, well documented solution available.  But it was overkill since I didn’t need status feedback and my time was very limited (backgroundRB setup seems somewhat involved).  And, I wasn’t sure how it would interact with Passenger mod_rails - although FooBarWidget mentioned on IRC that it should work as expected.

I looked at Spawn plugin which supports threading and forking ruby processes.   No luck - setting it one way never ran inside mod_rails and setting it the other way tied up the request response cycle.

All the ruby code was in place, except for how to detach this process from the request/response cycle, when severnspoon provided this
Simple, Easy, One-Line Solution:

My_Controller
  def generate_pdf_in_background
    system " RAILS_ENV=#{RAILS_ENV}   ruby  #{RAILS_ROOT}/script/runner   'MyModel.create_pdf_in_background'  &
  end
end

That ampersand was all I needed.  It runs the command as a background process.  A new ruby process is kicked off, and the 10 minute task runs perfectly.  Something makes the browser hang and wait for a response, but we confirmed that other requests can happen along side this.

No Comment

No comments yet

Leave a reply