admin管理员组

文章数量:1122846

I'm trying to determine if a job in my Rails application is running inline (i.e., synchronously) or asynchronously. How can an ActiveJob instance know if it was executed inline with perform_now or in the background with perform_later?

I know I can check the provider_job_id attribute, but I'm looking for a more Rails-way.

Is there a built-in method or attribute that I can use to check if an Active Job is running inline?

Here's an example of what I'm trying to do:

    class MyJob < ActiveJob::Base
      def perform
        if # job is running inline
          # do something
        else
          # do something else
        end
      end
    end

I'm trying to determine if a job in my Rails application is running inline (i.e., synchronously) or asynchronously. How can an ActiveJob instance know if it was executed inline with perform_now or in the background with perform_later?

I know I can check the provider_job_id attribute, but I'm looking for a more Rails-way.

Is there a built-in method or attribute that I can use to check if an Active Job is running inline?

Here's an example of what I'm trying to do:

    class MyJob < ActiveJob::Base
      def perform
        if # job is running inline
          # do something
        else
          # do something else
        end
      end
    end
Share Improve this question asked Nov 21, 2024 at 21:53 Tom RossiTom Rossi 12k7 gold badges72 silver badges99 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Try this custom approach:

class MyJob < ActiveJob::Base
  attr_accessor :running_inline

  before_enqueue do |job|
    job.running_inline = false
  end

  def perform(*args)
    if running_inline
      # Job is running inline
      puts "Running inline"
    else
      # Job is running asynchronously
      puts "Running asynchronously"
    end
  end

  def perform_now
    self.running_inline = true
    super
  end
end

本文标签: How to check if an Active Job is running inline in RailsStack Overflow