Jobs

Jobs classes are exclusively used for asynchronous processes. These jobs can be used for anything: from scheduled clean-ups, to billing charges, to mailings. Being asynchronous means that they will run in parallel of the main process.

With Ruby on Rails, we can use the ActiveJob rails class. In our own framework, we have a custom parent class called ApplicationJob which inherits from the rails class. All of our job classes then inherits from our own custom class.

By convention, every job classes must implement the perform method. This is the method that contains the code the job must process. Attenzione! To use a job, you have to call perform_later to schedule it.

Example

Here is what a job looks like:

class UsersCleanupJob < ApplicationJob
  def perform
    User.first.destroy
  end
end

In this dummy job, we destroy the first user. To execute this job, we can simply do:

UsersCleanupJob.perform_later

You can see that the naming of the method is not the same than the one we call. This is the convention we talked about: we declare the perform method in the job class and we call perform_later to enqueue it.

As you just saw, calling perform_later will enqueue the job and the executioner will process it when it is ready.

If you want more informations about that, check out the tips and documentation about Sidekiq.

Last updated