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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With