我有一个冗长的任务需要在我的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
任务花费很长时间才能完成。
我的活动作业设置有问题吗?
我明白了,谢谢。我误解了即时执行线。设置delayed_job,并将config.active_job.queue_adapter =:delayed_job添加到config/application.rb正在成功运行。 – aperture
是的,码头可能会好一点,API对我来说似乎有点神奇。查看CodeShip上的Leigh Halliday撰写的这篇伟大博客文章https://blog.codeship.com/how-to-use-rails-active-job/ –