Sunday, 6 November 2016

Background Jobs with Resque gem in Rails

It is very important in website building to keep your response times less. Long-running requests may be degrade server resource. In this situation we can perform some task in background using another resources.

Here we will use Resque for background job. Resque is a Redis-backed library for creating background jobs, placing those jobs on multiple queues, and processing them later.

Setting up Resque -

Hence, Resque is using Redis-backed library so we have to install first redis server -

Please follow the digital ocean link for installing redis https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04

Set Up Redis -

config/initializers/resque.rb -


ENV["REDISTOGO_URL"] ||= "redis://username:password@host:1234/"

uri = URI.parse(ENV["REDISTOGO_URL"])
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password, :thread_safe => true)


In Gemfile -


gem 'resque'
gem 'resque-web', require: 'resque_web'

Run bundle

Next include it in your application -

require 'resque'

Now we will create a queue for appointment receipt sender. For this create a folder of workers in app directory.

Create a file appointment_receipt_sender.rb -

class AppointmentReceiptSender
  @queue = :appointment_receipt_sender_queue
 
  def self.perform(appt_id)
    appt = Appointment.find appt_id
    client = appt.client

    AppointmentMailer.receipt_email(client).deliver
    appt.receipt_sent_at = Time.now
    appt.save
  end
end

In controller -

def appointment_receipt_sender
  Resque.enqueue(AppointmentReceiptSender, appt_id)
end

To start a worker, create a Rakefile in your app's root (or add this to an existing Rakefile):

require 'your/app'
require 'resque/tasks'

This will load the Resque tasks and load the environment which is required for doing any work.

To start a worker that will pull work off of all queues run the command:

$ rake resque:work QUEUE=*


Monitoring the Resque Queue

Open your config/routes.rb and mount the application like this:

require 'resque/server'

MyApp::Application.routes.draw do
  mount Resque::Server.new, at: "/resque"
end


Then restart your Rails server. Open up
http://localhost:3000/resque
in a browser to check out the web backend.

On the Overview tab you can see a list of the queues and workers. Each queue shows a count of pending jobs. The list of workers displays what queue(s) each worker is working on, and the job currently being processed (if any).





1 comment: