Rails has a new library called ActiveJob, the idea of this library is to make it easier to create background jobs without worring about what library to use, and the specific API for each one, and even changing it if a better one comes out in the future without changing your application.
ActiveJob will keep one simple API and it already provides an in memory implementation that you can use to test and in development environment, but do not forget to select a real driver for your production environment.
ActiveJob is so cool, that it out of the box, allows you to do things like this:
MyMailer.prepare_email(param1, param2, param3).deliver_later
And the email will be delivered by the job queue, and only this would already be a huge performance improvement for a lot of shitty web applications around.
Of course it is not just that, you can create your own jobs with the simple command:
rails g job MySuperComplexLogic
that will just create a file app/jobs/my_super_complex_logic_job.rb according to the name you’ve passed to the generator.
The file looks like any other Ruby class, because it is a simple ruby class as you can see bellow:
class MySuperComplexLogicJob < ApplicationJob queue_as :default def perform(*args) # Do something later end end
you simply implement the perform method, and when you want to invoke it, you will call:
MySuperComplexLogicJob.perform_later
And if you think the API looks really similar to Sidekiq, it is not by accident š
But the API is extended, you can also set options before calling the “perform_later” method, for example:
MySuperComplexLogicJob.set(queue: 'other').perform_later MySuperComplexLogicJob.set(wait: 5.minutes).perform_later(some,arguments) MySuperComplexLogicJob.set(wait_until: Time.now.tomorrow).perform_later
With this, you can delay the execution, set the time when it will run or even select the exact queue where the job will be executed, assumming the backend supports different queues.
After this, you just need to select wich background job implementation you’ll really use in production, and ActiveJob out of the box supports these backends:
I’m probably going with sidekiq, mostly because I’m already used to it, but if you do not like any of these, you can always write an adapter for your favorite backend.
If you have any questions about how to use ActiveJob or why to use it, please leave a comment bellow, or contact me by email ([email protected]).