Getting going with ActiveJob on Heroku
ActiveJob was introduced into Rails 4 to handle slower tasks that don’t want to hold up the web server. This functionality is available in older Rails versions although through non-core gems. I wanted to write up a quick guide to getting it running with Sidekiq on Heroku.
Installation
Install Redis: brew install redis
(more info about installing redis here)
Get the Sidekiq gem:
gem 'sidekiq'
Tell Rails to use Sidekiq as its ActiveJob queue adapter by adding this into application.rb:
config.active_job.queue_adapter = :sidekiq
Running in development
You’ll need a redis server running and a Sidekiq process.
Assuming you have successully installed redis, you can start it by running: redis-server
Run Sidekiq on your command line by running bundle exec sidekiq -q default -q mailers
. The -q mailers
argument ensure that the ActiveMailer queue is listened to.
Running background emails
ActionMailer already has ActiveJob plugged in. Once everything above is running, all you need to do is call UserMailer.welcome(@user).deliver_later
. This will add a mailer job to the queue (in Redis) and Sidekiq will pick it up and run the job. You should see a little activity in your Sidekiq and Redis output if you have it running.
I’ll add a bit about creating our own custom jobs shortly but there’s plenty of information around about that.
Deploying to Heroku
Add the Redis add-on and add a worker which will run the background activities. You can add a worker through the Heroku dashboard or through their command line tool.
Your Procfile will tell Heroku what to do. The web
line describes how to run the main web process. The important bit for the background tasks is the worker line. Here I’m telling it to run sidekiq with the default and the mailer queue.
web: bundle exec puma -C config/puma.rb
worker: bundle exec sidekiq -q default -q mailers