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 Sidekiq

Here's how you can use activejob with a sidekiq backend. Sidekiq uses redis as a storage backend so you'll need a redis server instance running.

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

$ rails new activejob-sidekiq

2. Add gem 'sidekiq' to your Gemfile.

3. Tell ActiveJob to use sidekiq

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

4. Setup sidekiq config in an initializer (config/initializers/sidekiq.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: a7cab7f4-9710-4832-940c-0c6fab83186a) to Sidekiq(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 sidekiq worker to run the job.

6. Starting a sidekiq worker

To start a sidekiq worker run bundle exec sidekiq:

$ bundle exec sidekiq
2015-03-08T20:39:53.515Z 3192 TID-ovtmzskjc INFO: Booting Sidekiq 3.3.2 with redis options {:url=>"redis://localhost:6379/5", :namespace=>"activejob-sample"}  
2015-03-08T20:39:54.279Z 3192 TID-ovtmzskjc INFO: Running in ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]  
2015-03-08T20:39:54.279Z 3192 TID-ovtmzskjc INFO: See LICENSE and the LGPL-3.0 for licensing details.  
2015-03-08T20:39:54.279Z 3192 TID-ovtmzskjc INFO: Upgrade to Sidekiq Pro for more features and support:  
2015-03-08T20:39:54.279Z 3192 TID-ovtmzskjc INFO: Starting processing, hit Ctrl-C to stop  

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: 343b7ff0-e9bd-4868-95d6-6408919b02f8) to Sidekiq(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [343b7ff0-e9bd-4868-95d6-6408919b02f8] Performing TestJob from Sidekiq(default) with arguments: 1, 2, 3
[ActiveJob] [TestJob] [343b7ff0-e9bd-4868-95d6-6408919b02f8] TestJob: I'm performing my job with arguments: [1, 2, 3]
[ActiveJob] [TestJob] [343b7ff0-e9bd-4868-95d6-6408919b02f8] Performed TestJob from Sidekiq(default) in 0.1ms

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

comments powered by Disqus