Tim Santeford
Tim Santeford

Reputation: 28131

Is it possible for Rails to close a client / browser connection but continue to execute in the background?

I have a relatively long task that must run in a controller action but does not need be completed before the view is rendered. How can I close the browser connection but continue the running the task? This seems like a common thing to do but I can find anything on SO or Google on how to do it.

TIA!

EDIT:

Would like to do the Rails equivalent of the following PHP code:

$contentLength = ob_get_length();

// these headers tell the browser to close the connection   
// once all content has been transmitted  
header("Content-Length: $contentLength");  
header('Connection: close'); 

// flush all output
ob_end_flush();
ob_flush();
flush();

// Finish the task.

Upvotes: 1

Views: 576

Answers (4)

Reinaldo Mendes
Reinaldo Mendes

Reputation: 21

In rails 3 do

class MyController < ApplicationController
   def index
     self.response_body = lambda do |response,output|
        5.times do |i| 
           response.write i
           sleep(2)
        end

     end
   end   
end

However you need fix a bug of rails 3

they executes 2 times the same lambda

include one file in config/initializers/rack_patch.rb

class Rack::Response
  def close
    @body.close if @body.respond_to?(:close)
  end
end

Upvotes: 1

noodl
noodl

Reputation: 17408

Two solutions have been pointed out so far. Those and others are listed in the Ruby Toolbox, here: http://ruby-toolbox.com/categories/queueing.html

Upvotes: 0

shingara
shingara

Reputation: 46914

You can use the resque gem too

Upvotes: 0

Ryan Bigg
Ryan Bigg

Reputation: 107728

Use the delayed_job gem for this. It allows you to specify background tasks to be run.

Upvotes: 0

Related Questions