There are times when you have to run certain tasks/jobs in background for your rails application.it can be as simple as sending emails, Http downloads, image resizing and much more.
Commonly used gems for Background processing
1. delayed_job (https://github.com/collectiveidea/delayed_job)
2. resque (https://github.com/defunkt/resque)
3. beanstalkd and stalker (http://http://kr.github.com/beanstalkd)
It totally depends on your needs and choice on which gem to choose for background job.But if your job queue is small with less failures i would suggest using delayed_job.
Here i would show you how i integrated delayed_job in my application for sending emails in background.
1. Installing delayed_job gem
Include the delayed_job gem in your gem file.
and run bundle install .
2. We need to run the generator
this would create a delayed_job migration.
Run this command on your terminal in your project directory.
after this we need to run the migration.
3. Queuing jobs
Now we need to call the delay method on any object to run the job in the background.
this is how my controller looks
class ContactsController < ApplicationController def create @contact= Contact.new(params[:contact]) if @contact.save UserMailer.delay.contact_information(@contact) UserMailer.delay.contact_confirmation(@contact) redirect_to root_path else render :action => 'new' end end end
Here you can see that I have called the delay method on UserMailer.So what we have done here is we have replaced the deliver method that we normally use for sending mail with delay method.
so instead of using UserMailer.contact_information(@contact).deliver
we use UserMailer.delay.contact_information(@contact)
4. Start the worker
In Development we can start this with this simple command
what this command will do is it will start the worker and start processing the jobs in the queue.
Great.but this won’t work in production and to make it working we need to run the delayed_job
script that is provided when we install the delayed_job gem. Its inside the /script directory.
Just run this command and it will start the worker in the background.
to start – ruby script/delayed_job start
to stop – ruby script/delayed_job stop
If you want to delete all the jobs in the queue. just run this command.
There’s a lot more that you can do in delayed_job but i have tried to keep this short. Kindly check the documentation for more options.
I hope you find this information useful when using delayed_job in your project.
Delivery Director, Thinker & Tinkerer at Idyllic.
Follow me on Twitter