Ruby on rails ActiveJob-what';MyJob.new.perform和MyJob.perform\u之间的区别是什么?
我发现ActiveJob可能由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::
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"
详细解释工作,如果你想了解更多关于工作如何工作的信息,这应该是一本有趣的书