5

我正在研究一种显示延迟作业完成百分比的解决方案(使用delayed_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

我在控制器方法中使用排队进程来延迟作业,并引用 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 不起作用。我看到了这个帖子中提出的 Delayed::Job.current 方法,但是看起来该方法从未包含在主要的delayed_jobs github项目中。

我如何访问当前作业(从实际作业中),以在每次作业通过循环时更新进度字段?

4

2 回答 2

10

It's to late to answer but I've faced with the same requirement so may be it will help someone. All you need to do is to implement custom job and before-hook where you will store reference on current job:

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

  def perform
    ...
    @job.update_attributes({ progress: your_progress_var }, without_protection: true)
  end
end
于 2014-06-26T09:08:04.380 回答
0

关于延迟工作的一件很酷的事情也是在这里阻碍你。当您将大量延迟的作业排队时,如果您有多个运行工作程序的实例,您可以并行处理它们 - 例如,您可以让 10 台机器运行您的应用程序的一个实例,访问同一个数据库并获得 10 倍的处理速度提升。因此,可能有多个“当前”工作。一次只运行一个作业是一种特殊情况。

这是一种查看所有活动作业状态的方法。如果您只运行一个实例,它只会返回一个作业,这样就可以满足您的情况:

active_jobs = Delayed::Job.where("progress > 0")
progress_of_first_job = active_jobs.first.progress if active_jobs.present?
progress_of_all_jobs = active_jobs.map{|job| job.progress}

progress_of_first_job 是其中一个作业的进度(使用 order 子句以确保安全)。progress_of_all_jobs 是每个活动作业的进度值数组(可能为空)。

于 2013-01-31T04:19:43.367 回答