Cristian Bica

Software Engineer

I’m Cristian Bica, a software engineer working for in/PACT. I'm working with ruby, rails, web frontend, iOS, Objective-C / Swift.

Howto: Using ActiveJob with Delayed::Job

Here's how you can use activejob with a Delayed::Job backend. Delayed::Job supports multiple adapter but the main one that is widely used is the ActiveRecord based one and I'm going to use it in this howto.

1. Create a new rails app (skip this if you're adding support for an existing app).

$ rails new activejob-delayedjob

2. Setup Delayed::Job.

Add the Delayed::Job gems to the Gemfile and run bundle install:

$ bundle install
Resolving dependencies...  
Using delayed_job 4.0.6  
Using delayed_job_active_record 4.0.3  
Bundle complete! 14 Gemfile dependencies, 59 gems now installed.  
Use `bundle show [gemname]` to see where a bundled gem is installed.  

Setup Delayed::Job:

$ rails generate delayed_job:active_record
      create  bin/delayed_job
       chmod  bin/delayed_job
      create  db/migrate/20150308210125_create_delayed_jobs.rb
$ rake db:migrate 
== 20150308210125 CreateDelayedJobs: migrating ================================
-- create_table(:delayed_jobs, {:force=>true})
   -> 0.0043s
-- add_index(:delayed_jobs, [:priority, :run_at], {:name=>"delayed_jobs_priority"})
   -> 0.0006s
== 20150308210125 CreateDelayedJobs: migrated (0.0050s) =======================

3. Tell ActiveJob to use Delayed::Job

You'll have to add config.active_job.queue_adapter = :delayed_job in your rails application configuration (application.rb, or development.rb/production.rb).

4. Setup Delayed::Job config in an initializer (config/initializers/delayed_job_config.rb)

5. Generate a job with rails generate job test and make the job log something

Now let's run a job:

$ rails runner "TestJob.perform_later(1,2,3)" 
[ActiveJob] Enqueued TestJob (Job ID: 03ecb892-5921-449d-bf3e-585f995c7222) to DelayedJob(default) with arguments: 1, 2, 3

We see the job was enqueued but it wasn't run. That's because we need to start a Delayed::Job worker to run the job.

6. Starting a Delayed::Job worker

To start a Delayed::Job worker run bundle exec rake jobs:work:

$ bundle exec rake jobs:work
[Worker(host:Cristians-MBP pid:4572)] Starting job worker

And finally let's enqueue a job and see what happens:

$ rails runner "TestJob.perform_later(1,2,3)"
[ActiveJob] Enqueued TestJob (Job ID: 64181fc1-91ba-4a44-9b5d-e51a228e9670) to DelayedJob(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [64181fc1-91ba-4a44-9b5d-e51a228e9670] Performing TestJob from DelayedJob(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [64181fc1-91ba-4a44-9b5d-e51a228e9670] TestJob: I'm performing my job with arguments: [1, 2, 3]
[ActiveJob] [TestJob] [64181fc1-91ba-4a44-9b5d-e51a228e9670] Performed TestJob from DelayedJob(default) in 0.05ms

... the job was performed :). Source code of a full app with the above implementation can be found on github:

comments powered by Disqus