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 Active Job with Resque

Here's how you can use activejob with a resque backend. Resque uses redis as a storage backend so you'll need a redis server instance running. For this howto I'm using a resque stable version (< 2.0).

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

$ rails new activejob-resque

2. Add gem 'resque' to your Gemfile.

3. Tell ActiveJob to use resque

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

4. Setup resque config in an intializer (config/initializers/resque.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)" && tail -n 1 log/development.log 
[ActiveJob] Enqueued TestJob (Job ID: ca18b21a-62b7-4207-abc9-1de761d4b8b9) to Resque(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 resque worker to run the job.

6. Starting a resque worker

First create a resque.rake file in the lib/tasks folder

Second start a worker:

$ LOGGING=1 QUEUE=* bundle exec rake resque:work
*** Starting worker Cristians-MBP:57718:*
*** Registered signals
*** Running before_first_fork hooks
*** Checking default
*** Sleeping for 5.0 seconds
*** resque-1.25.2: Waiting for *

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

$ rails runner "TestJob.perform_later(1,2,3)" && sleep 3 && tail -n 4 log/development.log
[ActiveJob] Enqueued TestJob (Job ID: 780f9874-0c19-44ff-934a-1f3852277db8) to Resque(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [780f9874-0c19-44ff-934a-1f3852277db8] Performing TestJob from Resque(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [780f9874-0c19-44ff-934a-1f3852277db8] TestJob: I'm performing my job with arguments: [1, 2, 3]
[ActiveJob] [TestJob] [780f9874-0c19-44ff-934a-1f3852277db8] Performed TestJob from Resque(default) in 0.12ms

... the job was performed :). Source code of a full app with the above implementation can be found on github: https://github.com/cristianbica/activejob-resque

comments powered by Disqus