I implemented batch processing in Rails using Whenever, so I will summarize it.
OS : macOS Mojave 10.14.6
ruby : 2.6.3p62
rails : 5.2.4
I want to create a task that runs regularly at a fixed time
Gemfile
gem 'whenever', require: false
Perform installation
Bundle install
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
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
$ bundle exec rails runner Batch::DeadlineClear.deadline_clear
Running via Spring preloader in process 77676
test
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
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