Delayed Job (DJ)

Table of Contents

We recommend not using delayed job for most applications due to the extra load generated on the database. Instead we recommend a Redis based queuing library.

Delayed Job, also known as DJ, makes it easy to add background tasks to your Rails applications on Heroku. You can also use Resque and many other popular background queueing libraries.
Delayed Job uses your database as a queue to process background jobs. If your app has a high database load using DelayedJob may not be a good background queueing library for your app. To get started using Delayed Job you need to configure your application and then run a worker process in your app.

Setting up Delayed Job

To use Delayed Job with PostgreSQL we’ll need to first add the gem to your Gemfile

gem 'delayed_job_active_record'

Run bundle install and then you need to create the table for queuing jobs.

$ rails generate delayed_job:active_record

Then migrate your database

$ rake db:migrate

You then need to tell your application to process jobs put into your job queue, you can do that by adding this to your Procfile:

worker: rake jobs:work

Now when you start your application locally it will start processing your job queue.

$ heroku local

Queuing jobs

Now that you have Delayed Job set up on your system you’ll want to put jobs in the queue. There are a few different ways to do this, for all of them refer to delayed_job documentation

Delayed Job adds a delay method to ActiveRecord objects causing that method to be executed in the background. So if you have a blog post model

Or you can delay that method by using the delay method which will add the method to the back of you queue.

Post.find(9).delay.send_to_twitter!

Queuing emails

Since sending email is not instantaneous it rarely makes sense to require a user to wait on it being sent. You can use the delay method on your mailers directly. So if we have a mailer called UserMailer and we are sending out a registration email it might look like this:

UserMailer.send_registration_mail(email, name).deliver

we can use the delay method on the mailer to send the email in a background task instead

UserMailer.delay.send_registration_mail(email, name)

It is considered a good practice to send all emails in the background.

Deploy

Now that our code is working locally, you’ll want to deploy your code to Heroku.