Rails 5 scheduler to update database once a day

前端 未结 1 778
闹比i
闹比i 2021-01-15 17:32

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

相关标签:
1条回答
  • 2021-01-15 18:08

    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.
    0 讨论(0)
提交回复
热议问题