[RUBY] [Rails] Regular batch processing by whenever

[Rails] Regular batch processing by whenever

I implemented batch processing in Rails using Whenever, so I will summarize it.

table of contents


Operating environment

OS : macOS Mojave 10.14.6 ruby : 2.6.3p62 rails : 5.2.4

Thing you want to do

I want to create a task that runs regularly at a fixed time

procedure

Install whenever

Gemfile


gem 'whenever', require: false

Perform installation

Bundle install

Add lib to rails

Set Rails to read the lib folder This is to put the files to be batch processed in the lib folder.

class Application < Rails::Application
  config.autoload_paths += Dir["#{config.root}/lib"]
end

Description of batch processing

Create a folder called batch in lib, and create a file to be executed regularly in it. Any name can be used after Batch ::.

Example batch/deadline_cleaner.rb

deadline_cleaner


class Batch::DeadlineClear
  def self.deadline_clear
    puts DateTime.now
    puts 'Test'
  end
end

Verification

$ bundle exec rails runner Batch::DeadlineClear.deadline_clear

Running via Spring preloader in process 77676
test

Create / edit schedule.rb

Go to the root folder of your application and run the following command

$ cd blog-app
$ bundle exec wheneverize .

When executed, config / schedule.rb will be created.

After that, describe the schedule and the task you want to execute in schedule.rb as shown below.

set :output, 'log/crontab.log'
set :environment, :development

every 1.day, at: '00:00 am' do
  runner 'Batch::DeadlineClear.deadline_clear'
end

Reflect it in CRON with the following command.

$ bundle exec whenever --update-crontab 

Execution result

You can see that the batch processing is actually done every minute.

$ cat log/crontab.log 
Running via Spring preloader in process 78244
2020-05-29T19:50:01+09:00
test
Running via Spring preloader in process 78534
2020-05-29T19:51:01+09:00
test
Running via Spring preloader in process 78598
2020-05-29T19:52:00+09:00
test
Running via Spring preloader in process 78652

Recommended Posts

[Rails] Regular batch processing by whenever
[Rails] Implementation of batch processing using whenever (gem)
How to make batch processing with Rails + Heroku configuration
[Rails 6] Validation by belongs_to
^, $ in Rails regular expression
Resolved strange HTML display by reviewing Rails dynamic processing
[Rails] I tried to implement batch processing with Rake task
Run Rails whenever with docker
Learn regular expressions little by little ①
Unit catcher made by Processing
[Docker] Use whenever with Docker + Rails
Rails singular resource routing by resource
[Rails] Implementation of coupon function (with automatic deletion function using batch processing)