2

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 after that time, such records must be inactive.(status active=false on DB). so basically it will run 2 SQL queries to fetch all records and then flag another field to inactive for records that are outdated.I'm working with Rails 5.

How should I go about this-gem(rufus,whatever,clockwork or any other gem) or simply some system tool for cronjob?I'm going to change my DB to PostgreSQL so will that impact? Any suggestions or sample code anyone can share to get an idea.

Means
  • 322
  • 2
  • 4
  • 16

1 Answers1

5

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.

  1. gem 'whenever', :require => false in Gemfile.
  2. Run bundle install
  3. run wheneverize command in terminal. This will create a schedule.rb file in config folder .
  4. Add the following code to schedule your rake task:

    every 1.day, at: '8:00 pm' do
      rake "my_namespace:task1"
    end
    
  5. Run this command: whenever --update-crontab. In case your environment is development, use command: whenever --update-crontab --set environment='development' (see this question.

  6. run crontab -l to check whether cron job has been added.
Community
  • 1
  • 1
abhi110892
  • 300
  • 1
  • 7
  • 1
    Let me know if you want a detailed explanation – abhi110892 Dec 06 '16 at 12:15
  • 1
    Yes, please, thanks. because the documentation only gives an overview but I'm not finding a relevant example that depicts how SQL commands will be written-in the rake command(s)...or both commands in a batch file and then run at one go with runner. – Means Dec 06 '16 at 13:25
  • 1
    I have updated the answer.Please let me know If u r still facing issues – abhi110892 Dec 07 '16 at 06:28