Rails是否可以关闭客户端/浏览器连接但继续在后台执行?

时间:2011-01-04 08:51:23

标签: ruby-on-rails ruby-on-rails-3

我有一个相对较长的任务,必须在控制器操作中运行,但不需要在呈现视图之前完成。如何关闭浏览器连接但继续运行任务?这似乎是常见的事情,但我可以在SO或Google上找到关于如何做的任何事情。

TIA!

修改

想要将Rails等效于以下PHP代码:

$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.

4 个答案:

答案 0 :(得分:1)

在rails 3中

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

但是你需要修复rails 3的错误

他们执行相同lambda的2倍

在config / initializers / rack_patch.rb中包含一个文件

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

答案 1 :(得分:0)

使用delayed_job gem进行此操作。它允许您指定要运行的后台任务。

答案 2 :(得分:0)

您也可以使用resque gem

答案 3 :(得分:0)

到目前为止已经指出了两种解决方案。这些和其他内容列在Ruby工具箱中,在这里:http://ruby-toolbox.com/categories/queueing.html