Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveJob - how to stop job from being enqueued in before_enqueue

I am running Rails 4.2.8 and I want to make my job only run under certain conditions. Currently I am doing that check in the code that is calling the job but it would be much cleaner to contain the logic in the job class. Has anyone done that?

class MyJob < ApplicationJob
  before_enqueue do |job|
    # check and stop job from being enqueued under certain conditions
  end
  def perform(args*)
    # code here
  end
end

I am using Sidekiq 4.2.10 as the background job adapter.

like image 310
Dmitry Polyakovsky Avatar asked Apr 14 '17 15:04

Dmitry Polyakovsky


People also ask

What is ActiveJob when should we use it?

Active Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.

What are async jobs in Rails?

In case of Async adapter, the job is executed asynchronously using in-process thread pool. AsyncJob makes use of a concurrent-ruby thread pool and the data is retained in memory. Since the data is stored in memory, if the application restarts, this data is lost. Hence, AsyncJob should not be used in production.

What is background job rails?

Running Background Jobs in Ruby on Rails Containers – DevGraph. Products. SCALEARC. A SQL load balancer that enables you to dramatically scale and improve database performance without any code changes to your application or database.

How do I enqueue a job in rails?

Enqueue jobs The different enqueuing options are the following: wait : With this, the job is enqueued after the mentioned time period. wait_until : With this, the job is enqueued after that the specified time has elapsed. queue : With this, the job is added to the specified queue.


2 Answers

You can use around_enqueue to achieve the same result without raising the exception. This can be useful when not enqueuing is something to be expected by your job.

Ex:

around_enqueue do |_job, block|
   if my_condition 
      block.call # this will enqueue your job
   end
end

OBS: Worth noting that this answer is based on Rails 5 ActiveJob code but must work on Rails 4 as well.

like image 131
Fabricio Buzeto Avatar answered Nov 15 '22 05:11

Fabricio Buzeto


throw :abort from your before_enqueue to halt the execution of the callback chain and perform.

Code: https://github.com/rails/rails/blob/fc20050ea69ba3b8d8bc90171d2dcbf93e9a1dae/activesupport/lib/active_support/callbacks.rb#L23

like image 23
Sergio Tulentsev Avatar answered Nov 15 '22 04:11

Sergio Tulentsev