Cron job in Ruby on Rails application – A Complete Tutorial for Beginners
A scheduled task is very important in Ruby on Rails application. Ruby on Rails does not have this type of “out-of-the-box” feature, but we can use the Cron job to achieve the purpose. Cron can be scheduled to send a reminder email, or scheduling to crawl something from another website on daily basis. In this blog, let’s quickly go through how to use Cron job.
What is CRON?
Cron task is a time-based job scheduler in Unix-like computer operating systems. Cron can be used to schedule jobs to run periodically at fixed times, dates, or intervals. Cron is most suitable for scheduling repetitive tasks in Ruby on Rails applications.
Let’s take the example of sending a daily digest email to persons or users. In this case, we might have a mailer like this using crontab:
#STEP 1.
The user can run any method from the terminal. Here I’m running an action inside a model i.e schedule_rb_method.
Open “app/models/reminder.rb” and then add the method for running action as shown below.
Run rails runner “Reminder.schedule_rb_method” command inside the project path on the terminal, to check method is running or not.
#STEP 2.
Set the default rvm to the project.
run rvm --default use 2.5.0
#STEP 3.
Creating a Crontab:
Cron is driven by a crontab (cron table) file, a configuration file that specifies shell commands to run periodically on a given schedule.
Users can have their own individual Crontab files in the system.
It’s pretty easy to start working with cron jobs in rails. You can start editing your cron tasks using the crontab command on your terminal:
Open your terminal: run crontab -e
This command will open a text file in your terminal’s default editor.
Comments
Post a Comment
Comments