I\'m new to rails and want to run a batch file/schedule task daily once at midnight that checks which entries have expired. Every record in the table has a closing_date and
In brief: You can use whenever Gem for this purpose.
You need to create a rake task for where you will write your SQL. Then schedule it as cron job using whenever
Detailed explanation
First step will be creating a rake task. You can do this using the console
rails g task my_namespace my_task1
This will create a file named my_namespace.rake
in the lib/tasks
folder with initial content like
namespace :my_namespace do
desc "TODO"
task task1: :environment do
# Your code will go here
end
end
You can check whether your task is running properly by running
rake my_namespace:task1
in the console.
Now you need to schedule the job using the whenever
gem.
gem 'whenever', :require => false
in Gemfile
.bundle install
wheneverize
command in terminal. This will create a schedule.rb
file in config folder .Add the following code to schedule your rake task:
every 1.day, at: '8:00 pm' do
rake "my_namespace:task1"
end
Run this command: whenever --update-crontab
. In case your environment is development, use command: whenever --update-crontab --set environment='development'
(see this question.
crontab -l
to check whether cron job has been added.