googleads
How To Use Active Job In Rails | Hire Ruby On Rails Developer
preloder
Ruby Ruby on Rails

Active Jobs In Rails – Ruby On Rails Guide

Active Job is introduced in Rails 4.2 version, Active Job in Rails is a framework for creating, scheduling and executing background Jobs.

What are background Jobs?

The tasks whose execution takes place outside of your normal flow of request-response cycle are the background tasks, these tasks will run parallel to your rails application.

Why we need background Jobs?

For example, your business requirement includes sending a notification email to all your registered users, let us say there are thousand registered users, let us consider it takes 1 second to send an email to the single user, so for sending 1000 users it will take 1000 seconds which is equal to 17 minutes approximately. So you need to wait for 17 minutes to complete the task, this 17 minutes you cannot access any web page of your application since it stops the execution of the task. Practically no user will prefer to wait for that much time without accessing some other web pages of your application.
If you implement the same using background Jobs Since these tasks will run parallelly outside of normal flow of request-response cycle so you no need to wait long for the task to get complete and also you can able to access the other pages of your application too.

When we can use background jobs:

We can use background jobs depending upon the business requirement, and If you want to send a notification email to all users about your latest product then you can go for background jobs, If you want to send your recently published article to all registered users then in that case you can preferably use background jobs likewise it can be applied in some other cases too.

How to create a background Job

We can create Active Job by rails generator using the command

 

The above generator will create a file in app/jobs folder, and it also creates a test case in test/jobs
You can also create a Job without the generator, create a file under app/jobs and inherit your class from ApplicationJob. The file looks in the following manner.

File: app/jobs/send_notifications_job.rb looks in following manner

 

Tips: How To Embed The JW Player Into Website

 

Queueing the Job

If you want to perform your job whenever the queuing system is free then use the below command,

 

Note: perform_later and perform_now will call the perform method of your Job. You can also pass as many parameters as you want in the perform method of your Job. You can also schedule your Job, for example, If you want to perform your job after 1 day from now.

 

You can also set your Job to be performed after 30 minutes from now.

 

Executing The Job

By Default Rails will provide in-process queuing system, in which it keeps the jobs in RAM. The disadvantage of this is, if the machine crashes or if we restart the system, it will cause the loss of existing jobs in the queue. To overcome this disadvantage, you need to add some third party queuing backend where you can queue your Jobs.
There are several built-in adapters of Active Job-like Sidekiq, Resque, Delayed Job, etc. You can choose any one of the built-in adapters as your queuing backend. Here is the list of all adaptors for ActiveJob.

Installing And Configuring the Queuing Backend

Install any of the built-in adapters of the Active job like sidekiq, resque, delayed job, etc. The installation procedure is different for different adapters, please follow specific adapters documentation for installation.

For Sidekiq, please follow the https://github.com/mperham/sidekiq/wiki/Active-Job doc
For Resque, please follow the https://github.com/resque/resque/wiki/ActiveJob

After adding adapter gem to your application, you need to configure the application.rb.

File: app/config/application.rb

Here I am using Sidekiq adapter,

So I configured with sidekiq in the config.active_job.queue_adapter, If you are using different adapter, please use that adapter name in the place of sidekiq. Also, if you want to use different queuing backend for specific Job, you can set your queuing backend as follows.

This job uses ‘resque’ as its backend queue adapter, It overrides the adapter which you have set in application.rb
Note: before adding the adapter name make sure that you installed adapters gem and followed the installation procedure.

Related: 10 Useful Tips & Tricks for Ruby On Rails Developers

 

Example:

We can do a simple task to send an email to all the registered users using a background job.
Let us consider our business requirement is to send a notification email to all registered users after successful creation of the new article.

I hope you have Ruby on Rails environment setup, next

1) create a simple new rails application by using the command rails new application-name. It will take some time to create your application.

2) Goto the application by cd application-name

3) Add the any one of the adapter gem to your gemfile; we can use sidekiq adapter, so add the line gem ‘sidekiq’ to your gemfile

4) Run the bundler by using the command bundle install

5) Create a user model and database table by using the command rails generate model User name:string email:string

6) Create an article model and database table by using the command rails generate model Article title:string description:text

7) Since we created user table and article table, now run rake db:migrate

8) Now user table is ready, goto rails console by typing rails c in the terminal

9) Create 3 or 4 dummy users but give the valid email address(since we have to send email to that email address). Use this command to create new user User.create(name:’wxyz’, email: ‘valid-email-id’) through rails console, to create multiple users use the same command by changing the name and email.

10) Now you have created users successfully, try User.all command, it should return all the users which you have created.

11) Since our requirement is sending email to users after creating Article, define an Article Controller by using the command rails generate controller Articles new, this command will create a articles controller with one method ‘new,’ it also create new.html.erb under views.

12) We will use Action Mailer to send emails, and Action Mailer allows you to send emails from your application

13) Create an UserMailer by Action Mailer generator; rails generate mailer UserMailer

14)  Open your application mailer file and configure default from address, the sender address of all your emails will be the address which you provided in default form. Your file should be as follows

File: app/mailer/application_mailer.rb

 

 

File: app/config/environments/development.rb

15) Open your development.rb file and give SMTP settings and configure your from address email details

16) In order to send email to users from your development environment you need change some Gmail settings of receiver email addresses, since Google has increased its security measures it blocks your call as your application is less secure now, click on this link, sign in to your Gmail account and on the Less Secure app access Setting. You will not face this issue in your production environment.

If you enabled less secure app access, it would be like as shown in below image

Now we have done all our configurations to send email, and next step is to define a method in app/mailers/user_mailer.rb
I defined a method called send_notification_email which will collect all the user emails and send an email to that email addresses.

File: app/mailers/user_mailer.rb

We can define the email body by creating the view file under app/views/UserMailer. To create a new file under UserMailer in views, the name of the view file should be same as the method name.

File: app/views/Usermailer/send_notification_mail.html.erb

 

15. Our task is to send emails as a background Job using Active Job after creating article successfully in our database. So open your Articles Controller which is located at app/controllers/articles_controller

File: app/controllers/articles_controller

 

new method: This method is used to render the article form for creating the article
show method: This method is used to show the article based on article Id
create method: This method is used to create the article into the articles table, after successful creation we are calling the active job to trigger email, we will see sendNotificationsJob method in upcoming files
article params: This method is used for defining the article parameters
Each method has separate view files which will be under app/views/articles/

File: app/views/articles/new.html.erb

 

This erb template simply renders the form for creating new article.

File: app/views/articles/show.html.erb

 

This erb template simply displays Article title and Article Description based on Article Id present in URL. Now it is the time to configure the routes.

Open your app/config/routes.rb file and configure your routes as follows

 

Now it is the time to define Background Job.

Open app/jobs/send_notifications_job.rb file and write the code to call the UserMailer’s send_notification_mail method, we are calling this perform method inside the articles controller after creating an article.(see articles_controller code).
File: app/jobs/send_notifications_job.rb

Perform method of SendNotificationsJob will call the userMailer send_notification method.

That’s it we have done all our coding part, now it is the time to execute our code, start your server by using rails s command in terminal. After starting server, access your application using localhost:3000 in the browser.

You can see the above form in your browser, Since we are concentrating only on Active Job functionality, I have not added any styles to the application.

After entering some sample data in the Article, click create Article button, this will save the record in database and redirect to show template as follows.


If you check the emails which you provided at the time of creating users, you will find the new email in your inbox which you triggered from your application. Here is the log file of Active Job.

Here are the emails which I received from my application,

I hope you understand how we can send email notifications as a background task using Active Job.

Hope this helps you! Similarly you can learn more on interesting on latest technologies, never miss out anything from Our largest blog portal where you can get continuous blog updates & latest posts about all the latest technologies which would be perfect for your 15 minutes tea break! In case if you’re a newbie then don’t forget to subscribe us to get the latest updates from diverse technologies. What else guys hit the  subscribe link  and go crazy over learning.

For more inquires reach us via info@agiratech.com

The following two tabs change content below.

Venkata Krishna

An ideal full stack software developer having 2 years of experience in Web app development and expertise in Ruby on Rails, CMS services. Let it be a technology or charity he never fails to feed the needy. An honest individual who continuously involves himself in creating Social Awareness as part of his life goals.

Leave a Reply

Your email address will not be published. Required fields are marked *

[contact-form-7 id="120788" title="Web Page Form"]

Schedule Your Call