Rails 5 scheduler to update the database once a day

I am new to rails and want to run a batch file / schedule task daily at midnight that checks which records have expired. Each record in the table has a clos_date value, and after that such records must be inactive (status active = false in the database). so it will basically run 2 SQL queries to fetch all records and then flag another field to inactive for stale records. I am working with Rails 5.

How do I go about this - a gem (rufus, whatever, clockwise or any other gem) or just a system tool for a cronjob? I'm going to change my DB to PostgreSQL, will this affect? Any suggestions or code examples to share to get an idea.

+1


source to share


1 answer


In short: you can use any time Gem for this purpose.

You need to create a rake task where you will write your SQL. Then schedule it as a cron job using


Detailed explanation

The first step is to create a rake problem. You can do this with the console

rails g task my_namespace my_task1 

      

This will create a file named my_namespace.rake

in the lib/tasks

original content folder like



namespace :my_namespace do
  desc "TODO"
  task task1: :environment do
    # Your code will go here
  end

end

      

You can check if your task is working correctly by running

rake my_namespace:task1 

      

in the console.

Now you need to schedule a job with a gem whenever

.

  • gem 'whenever', :require => false

    in Gemfile

    .
  • Run bundle install

  • Run the command wheneverize

    in a terminal. This will create a file schedule.rb

    in the config folder.
  • Add the following code to schedule the rake task:

    every 1.day, at: '8:00 pm' do
      rake "my_namespace:task1"
    end
    
          

  • Run this command: whenever --update-crontab

    . If your environment is development use the command: whenever --update-crontab --set environment='development'

    (see this question .

  • run crontab -l

    to check if a cron job has been added.
+3


source







All Articles