使用ActiveJobs排队Delayed_Job

时间:2016-07-05 18:36:21

标签: ruby-on-rails delayed-job rails-activejob

在控制器中,我有一个经过身份验证的用户发出ActiveJob的帖子请求。

RunReportsJob.perform_later(param1, param2, param3)

它没有错误。但是,如果用户再次按下按钮(触发发布请求)以在RunReportsJob已经运行时触发,则会同时发生2个作业。我设置了delayed_job,因为我认为它是一个排队服务,并且会一次保持一项工作。但这不会发生。以下是我的配置:

# app/jobs/run_reports_job.rb:

class RunReportsJob < ActiveJob::Base
      queue_as :RunReports
      include ShopifyApp::Controller
      # --------------------------------------------------------------
      # JOB ERROR MANAGEMENT
      # --------------------------------------------------------------
      rescue_from(ActiveRecord::RecordNotFound) do |exception|
           # Do something with the exception
           logger.debug "Hit rescue_from"
      end
      # --------------------------------------------------------------
      # JOB FUNCTION
      # --------------------------------------------------------------
      def perform(param1, param2, param3)
        # some code is performed here
      end
 end

# config/application.rb

config.active_job.queue_adapter = :delayed_job

# config/initializers/delayed_job_config.rb

Delayed::Worker.max_attempts = 1
Delayed::Worker.max_run_time = 12.hours

1 个答案:

答案 0 :(得分:1)

您必须在RunReportsJob.perform_later(param1, param2, param3)之前添加一些逻辑来检查已排队的作业优先级并增加优先级编号(根据文档,较低的数字是较高的优先级)在本例中的队列:

highest_priority = Delayed::Job.where(queue: :RunReports).maximum(:priority)
Delayed::Worker.default_priority = highest_priority + 1 if highest_priority

RunReportsJob.perform_later(param1, param2, param3)

DelayedJob使用表来保存所有工作信息,请查看https://github.com/collectiveidea/delayed_job#gory-details上的文档