我正在研究一种解决方案,以显示延迟工作的完成百分比(使用delay_job gem)。目前,我已对我的delay_jobs表进行了数据库迁移,如下所示:

class CreateDelayedJobs < ActiveRecord::Migration
  def self.up
    create_table :delayed_jobs, :force => true do |table|
      table.integer  :priority, :default => 0      # Allows some jobs to jump to the front of the queue
      table.integer  :attempts, :default => 0      # Provides for retries, but still fail eventually.
      table.text     :handler                      # YAML-encoded string of the object that will do work
      table.text     :last_error                   # reason for last failure (See Note below)
      table.datetime :run_at                       # When to run. Could be Time.zone.now for immediately, or sometime in the future.
      table.datetime :locked_at                    # Set when a client is working on this object
      table.datetime :failed_at                    # Set when all retries have failed (actually, by default, the record is deleted instead)
      table.string   :locked_by                    # Who is working on this object (if locked)
      table.string   :queue                        # The name of the queue this job is in
      table.integer  :progress
      table.timestamps

    end

    add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'
  end

  def self.down
    drop_table :delayed_jobs
  end
end

我在 Controller 方法中使用入队进程来处理延迟的工作,并引用lib/build_detail.rb中的类:
Delayed::Job.enqueue(BuildDetail.new(@object, @com))

lib/build_detail.rb文件如下:
class BuildDetail < Struct.new(:object, :com)

  def perform
    total_count = object.person_ids.length
    progress_count = 0

    people = com.person object.person_ids do |abc|
      progress_count += abc.size
      Delayed::Job.current.update_attribute :progress, (progress_count/total_count)
    end
  end

end

Delayed::Job.current不起作用。我看到了this posting上提出的Delayed::Job.current方法,但是看来该方法从未包含在主要的delay_jobs github项目中。

每当工作循环时,如何访问当前工作(从实际工作中)以更新进度字段?

最佳答案

现在回答还为时已晚,但是我也面临着同样的要求,因此可能会对某人有所帮助。
您需要做的就是实现自定义作业和before -hook,您将在其中存储当前作业的引用:

class MyTestJob
  def before(job)
    @job = job
  end

  def perform
    ...
    @job.update_attributes({ progress: your_progress_var }, without_protection: true)
  end
end

09-05 11:38