Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveJob-what';MyJob.new.perform和MyJob.perform\u之间的区别是什么?_Ruby On Rails_Rails Activejob - Fatal编程技术网

Ruby on rails ActiveJob-what';MyJob.new.perform和MyJob.perform\u之间的区别是什么?

Ruby on rails ActiveJob-what';MyJob.new.perform和MyJob.perform\u之间的区别是什么?,ruby-on-rails,rails-activejob,Ruby On Rails,Rails Activejob,我发现ActiveJob可能由MyJob.new.perform和MyJob.perform\u now触发 我的问题是:这两个调用之间有什么区别?现在执行perform\u方法是ActiveJob::Execution类的perform方法的包装器。可以找到这两种方法的源代码(答案缩写)。源代码如下: module ActiveJob module Execution extend ActiveSupport::Concern include ActiveSupport::

我发现ActiveJob可能由
MyJob.new.perform
MyJob.perform\u now
触发


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

现在执行
perform\u
方法是
ActiveJob::Execution
类的
perform
方法的包装器。可以找到这两种方法的源代码(答案缩写)。源代码如下:

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

我的工作。立即执行 此调用调用类方法
perform\u now
(代码段中的方法1),该方法在内部实例化
MyJob
的对象,并调用实例方法
perform\u now
(代码段中的方法2)。如果需要,此方法将参数反序列化,然后运行我们在作业文件中为
MyJob
定义的回调。在此之后,它调用
perform
方法(我们的代码片段中的方法3),这是
ActiveJob::Execution
类的一个实例方法

MyJob.new.perform 如果我们使用这种表示法,我们基本上是自己实例化一个作业实例,然后在作业上调用
perform
方法(代码片段的方法3)。通过这样做,我们跳过了
perform\u 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.new.perform
给出了以下输出:

"I'm in the before perform callback"
"I'm performing the job"
"I'm performing the job"
详细解释工作,如果你想了解更多关于工作如何工作的信息,这应该是一本有趣的书