2016-05-23 36 views
4

我有一個冗長的任務需要在我的Rails 4.2.6應用程序的後臺運行。不幸的是,這項工作並沒有使用Active Job發送到後臺。我已經產生的任務:Rails活動作業:perform_later不在後臺執行

class PhotoProcessorJob < ActiveJob::Base 
    queue_as :default 
    def perform(*args) 
    ::Photo.process_photos 
    end 
end 

其中呼籲我的照片類中的方法(存儲在配置/初始化):

class Photo 
    require 'zxing' 
    require 'csv' 

    @tablePath = Dir.glob("#{Rails.root.to_s}/tmp/photo_processing/*.csv")[0] 
    @output = "#{Rails.root.to_s}/tmp/photo_data.csv" 

    def self.getStudentInfo(id) 
    CSV.foreach(@tablePath, headers: true) do |row| 
     if row["Student ID"] == id 
     return row 
     else 
     next 
     end 
    end 
    end 

    def self.writeInfoToFile(data, file) 
    first_name = data["First Name"] 
    last_name = data["Last Name"] 
    student_id = data["Student ID"] 
    grade = data["Grade"] 
    email = data["Email"] 
    photo = file.to_s 
    CSV.open(@output, "a+") do |csv| 
     csv << [first_name, last_name, student_id, grade, email, photo] 
    end 
    end 

    def self.process_photos 
    extensions = %w(.jpg .jpeg .png .gif .tif) 
    studentInfo = nil 
    newfile = false 
    if File.exist?(@output) 
     outfile = CSV.new(File.read(@output)) 
     if outfile.count == 0 
     newfile = true 
     end 
    else 
     newfile = true 
    end 
    if newfile 
     CSV.open(@output, "wb") do |csv| 
     csv << ["First Name", "Last Name", "Student ID", "Grade", "Email", "Photo"] 
     end 
    end 
    Dir.glob("#{Rails.root.to_s}/tmp/photo_processing/*").each do |file| 
     if file.match(/#{extensions.join("|")}/) 
     id = ZXing.decode File.new(file) 
     unless id.nil? 
      studentInfo = getStudentInfo(id) 
     else 
      writeInfoToFile(studentInfo, file) unless studentInfo.nil? 
     end 
     end 
    end 
    end 

end 

以及來自控制器名爲:

class ProcessingController < ApplicationController 
    def finish 
    PhotoProcessorJob.perform_later 
    end 
end 

我試圖使用Active Job Inline後端,因此沒有安裝任何隊列庫。問題是,「finish」視圖在process_photos方法運行時被延遲,而不是被髮送到後臺並立即顯示視圖。這會導致Nginx中的502錯誤,由upstream prematurely closed connection造成,可能是因爲process_photos任務花費很長時間才能完成。

我的活動作業設置有問題嗎?

回答

7

引述文檔:

Rails的默認配備了一個「立即亞軍」排隊的實現。這意味着每個已經入隊的工作都會立即運行。

這意味着默認情況下,活動作業將在主線程中運行,而不是在「背景」中運行。這是一個常見的問題。基本上有效的工作只是跨多個排隊後端的通用API。

TL; DR您必須設置一個類似Sidekiq的排隊後端。

否則,你的設置看起來不錯,甚至教科書。

+2

我明白了,謝謝。我誤解了即時執行線。設置delayed_job,並將config.active_job.queue_adapter =:delayed_job添加到config/application.rb正在成功運行。 – aperture

+0

是的,碼頭可能會好一點,API對我來說似乎有點神奇。查看CodeShip上的Leigh Halliday撰寫的這篇偉大博客文章https://blog.codeship.com/how-to-use-rails-active-job/ –