Schedule Tasks With Ruby on Rails
“There cannot be a crisis next week. My schedule is already full.” This cheeky quote by Henry Kissinger explains the importance of having a schedule. In life or in tech, scheduling are important.
When it comes to Ruby on Rails which prefers convention over configuration, a scheduler is a must. Scheduling job can be defined as “a decision process of committing resources between varieties of tasks”. It is basically a function enabling one to perform routine tasks as part of a sequence or during predefined time like performing maintenance operations on retrieving RSS feeds. These scheduled jobs which are performed in the background are executed by ‘workers’.
So what are the best ways to schedule a task in Rails environment? Usually, developers can use application specific cron jobs to run the tasks however, cron jobs are for scheduling things, not actually performing them. It also works well on a single server but in case you want to scale to multiple server, it doesn’t work that good. They are also difficult to debug and are time consuming. So, how can you ensure that your scheduling works well and without any dependency or too much syntax. ‘Whenever’ comes to your rescue! Check out how ‘whenever’ gem can help you create cron jobs with Ruby.
What is Whenever gem?
It is used for writing and deploying corn jobs with clear syntax.
How to Install it?
gem ‘whenever’, :require => false
After Installation We have to type “wheneverize .” in console.Then automatically this will create schedule.rb file inside the config folder.
Inside the schedule.rb file we can schedule the function based on time,date,month,etc..
Ex:
every 1.day, :at => ’10:00 am’ do
rake “sow:events_reminder_mail”, :environment => :development
end
Before scheduling the action Inside the lib folder we have to create one task folder, inside the task folder we can create rake file.That rake file name only we have to use for scheduling the action
rake “sow:events_reminder_mail”, —–> rake file name with task Name
:environment => :development ——–> We have to specific the Environment
Inside the rake file we can give the condition and use User Mailier for sending the email.That User Malier will send the mail based on scheduling time,date,month,etc..
Ex:()
desc “Events Inactive”
task :events_inactive => :environment do
@events = Event.where(:end_date=>Date.today-1.days)
@events.each do |event|
event.update_attributes(:published_status=>false,:inactive_dat e=>Date.today)
end
end
Reference : https://github.com/javan/whenever