ActiveJob - MyJob.new.perform 和 MyJob.perform_now 有什么区别?

ActiveJob - what's the difference between MyJob.new.perform and MyJob.perform_now?

我发现 MyJob.new.performMyJob.perform_now 可以触发 ActiveJob。

我的问题是:这两个调用有什么区别?

perform_now 方法是 ActiveJob::Execution class 的 perform 方法的包装器。可以找到这两种方法的源代码(缩写为答案)here on GitHub。源码如下:

module ActiveJob
  module Execution
    extend ActiveSupport::Concern
    include ActiveSupport::Rescuable

    # Includes methods for executing and performing jobs instantly.
    module ClassMethods
      # Method 1
      def perform_now(*args)
        job_or_instantiate(*args).perform_now
      end
    end

    # Instance method. Method 2
    def perform_now
      self.executions = (executions || 0) + 1

      deserialize_arguments_if_needed
      run_callbacks :perform do
        perform(*arguments)
      end
    rescue => exception
      rescue_with_handler(exception) || raise
    end

    # Method 3
    def perform(*)
      fail NotImplementedError
    end

MyJob.perform_now 这个调用,调用了class方法,perform_now(代码片段中的方法1),它在内部实例化了MyJob的一个对象,并调用实例方法perform_now(代码片段中的方法2)片段)。如果需要,此方法反序列化参数,然后运行我们可能在作业文件中为 MyJob 定义的回调。在此之后,它调用 perform 方法(我们代码段中的方法 3),这是 ActiveJob::Execution class.

的实例方法

MyJob.new.perform 如果我们使用这种表示法,我们基本上是自己实例化作业的一个实例,然后在作业上调用 perform 方法(我们代码段的方法 3)。通过这样做,我们跳过 perform_now 提供的反序列化,也跳过 运行 在我们的作业 MyJob 上编写的任何回调。

举例说明:

# app/jobs/my_job.rb

class UpdatePrStatusJob < ApplicationJob
  before_perform do |job|
    p "I'm in the before perform callback"
  end

  def perform(*args)
    p "I'm performing the job"
  end
end

MyJob.perform_now 给出输出:

"I'm in the before perform callback"
"I'm performing the job"

MyJob.new.perform 给出输出:

"I'm performing the job"

This article by Karol Galanciak 详细解释了工作,如果您正在寻找有关工作如何运作的更多信息,应该是一本有趣的读物。