Rails 5 scheduler to update database once a day

2020-03-28 02:47发布

问题:

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.

回答1:

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.