Rails 4.2 has a built-in support for executing jobs/tasks in the background using Active Job. This framework helps to setup jobs to be executed by workers at a later time by queuing in back-end. Active Jobs manages jobs in front-end and it allows queuing in back-end using Delayed Job (DJ) or Sidekiq or Resque. We'll be using Active Jobs with DJ queuing in back-end, since we already use DJ. Moreover, Rails 5 is expected to support inbuilt queuing.(https://github.com/rails/rails/pull/19425).
Present gems stack:
1. Initialize Active Job to use Delayed Job as back-end in Rails application configuration (application.rb or development.rb/production.rb).
config.active_job.queue_adapter = :delayed_job
2. Taking an existing Learnexa worker class 'DisableUserSubscription' as example:
class DisableUserSubscription
attr_accessor :company_id
def initialize(company_id)
self.company_id = company_id
end
def perform
UserSubscription.disable_user_subscription(self.company_id)
end
end
3. Correcting the above class in Active Jobs style. A new class will be generated using:
rails g job DisableUserSubscription
Above command will create a new class which is descendant of ActiveJob::Base with name ending with Job.
4. Change #perform method as:
class DisableUserSubscriptionJob < ActiveJob::Base
queue_as :default
def perform(company_id)
UserSubscription.disable_user_subscription(company_id)
end
end
5. Replacing Delayed Job queuing code:
Delayed::Job.enqueue DisableUserSubscription.new(@company.id)
as
DisableUserSubscriptionJob.perform_later(@company.id)
Active Job also contains a useful module ActiveJob::TestHelper, which provides several useful methods to verify that the jobs are working properly. Some significant ones are:
1. assert_enqueued_jobs(number) - checks that exact number of jobs were added to queue
assert_enqueued_jobs 1 do post :create end
2. assert_enqueued_with(args) - checks that block enqueues job with given arguments
assert_enqueued_with(job: DisableUserSubscriptionJob,
args: [company],
queue: 'default') do
post :create
end
3. perform_enqueued_jobs - performs jobs created in the past block instead of queuing them
perform_enqueued_jobs do post :create end
Adding Active Jobs and deleting Delayed jobs shouldn't be done in same deployment. Because, the previously used worker might get delayed but not be processed fully before deployment. And after deployment this job fails because Delayed Job couldn't create instance of already deleted class.
A few significant benefits are:
Reference: