【发布时间】:2016-09-20 19:26:39
【问题描述】:
我有一个冗长的任务需要在我的 Rails 4.2.6 应用程序的后台运行。不幸的是,该作业没有使用 Active Job 发送到后台。我已经生成了一份工作:
class PhotoProcessorJob < ActiveJob::Base
queue_as :default
def perform(*args)
::Photo.process_photos
end
end
调用我的 Photo 类的方法(存储在 config/initializers 中):
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 后端,因此没有安装任何队列库。问题是“完成”视图在 process_photos 方法运行时被延迟,而不是被发送到后台并立即显示视图。这导致由upstream prematurely closed connection 引起的Nginx 内出现502 错误,大概是因为process_photos 任务完成时间过长。
我的 Active Job 设置有问题吗?
【问题讨论】:
标签: ruby-on-rails rails-activejob