Active Job , Sidekiq And Redis In Rails 4

activejob_sidekiq
activejob_sidekiq

Active Job is a framework for declaring jobs and making them run on a variety of queueing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.

Sidekiq simple, efficient background processing for Ruby. Sidekiq uses threads to handle many jobs at the same time in the same process. It does not require Rails but will integrate tightly with Rails 3/4 to make background processing dead simple.

Redis :-

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperlog logs.

Other features include :-  

  1. Transactions
  2. Pub/Sub
  3. Lua scripting
  4. Keys with a limited time-to-live
  5. LRU eviction of keys
  6. Automatic failover

Installation :-

  1. wget http://download.redis.io/redis-stable.tar.gz
  2. tar xvzf redis-stable.tar.gz
  3. cd redis-stable
  4. make
  5. redis-server

Integrating Sidekiq with Rails :-

Gem file

  1. activejob_backport
  2. sidekiq-cron
  3. sinatra
  4. slim

application.rb

Add this line to configure the sidekiq

include Sidekiq::Worker

config/initializer/active_job_configuration.rb

ActiveJob::Base.queue_adapter = :sidekiq

config/sidekiq.yml

:concurrency: 25

:pidfile: ./tmp/pids/sidekiq.pid

:logfile: ./log/sidekiq.log

:queues:

– default

– [high_priority, 2]

 

config/routes.rb

require ‘sidekiq/web’

mount Sidekiq::Web, at: ‘/sidekiq’ , constraints: ->(request) {SideKiqConstraint.authenticate?(request)}

Note:- SideKiqConstraint.authenticate?(request) is the method which authenticate and ensure only user with role excelfore is able to see sidekiq GUI.

class SideKiqConstraint

def self.authenticate?(request)

if (!request.session[‘user_id’].blank? and !(user= User.find_by(id:request.session[‘user_id’])).blank?)

return user if user.excelfore?

end

end

end

Command to start sidekiq

In Development

sidekiq -C config/sidekiq.yml

In Production

bundle exec sidekiq -d -L sidekiq.log -q mailer,5 -q default -e production

The above steps ensure sidekiq to work background jobs. Now lets see the steps to setup sidekiq for the cron jobs.

config/schedule.yml

my_first_job:

 cron: “*/1 * * * *”

 class: “SidekiqClock1”

Add the below code in config/initializer/active_job_configuration.rb to load the jobs from the schedule.yml file

schedule_file=”config/schedule.yml”

if File.exists?(schedule_file)

Sidekiq::Cron::Job.load_from_hash YAML.load_file(schedule_file)

end

Sample cron job method:-

class SidekiqClock1

include Sidekiq::Worker

def perform

ActionMailer::Base.mail(to: ‘gurudath@gurudath.com’ ,subject: ‘Process Completed’,body:’Gurudath Test’,from:”xbass@gurudath.com”).deliver

end

end