Delete a certain number of books posted every 3 minutes.
・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
GemGemfile
gem 'whenever', require: false
Terminal
$ bundle install
$ bundle exec wheneverize //config/schedule.rb file generated
" data_reset.rb "app/lib/batch/data_reset.rb
class Batch::DataReset
  def self.data_reset
    Book.delete_all  #Delete books in database
  end
end
◎ If you want to specify the id, write the following
Book.where.not (id: 1..30) .delete_all: Delete all except id1 ~ 30
◎ If you want to delete the data after the creation date (after December 1st), enter the following
Book.where("books.created_at < ?", "2020-12-1").delete_all
"config/application.rb "config/application.rb
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.paths.add 'lib', eager_load: true #Add here
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
Modify the above file to enable " data_reset.rb "
Terminal
bundle exec rails runner Batch::DataReset.data_reset //data_Check if reset is done
Terminal
Running via Spring preloader in process [Process ID] //If it appears like this, it is a success
" schedule.rb "config/schedule.rb
:
:
require File.expand_path(File.dirname(__FILE__) + "/environment")
rails_env = Rails.env.to_sym
set :environment, rails_env  #Specify a relative path from an absolute path
set :output, 'log/cron.log' #Set the log output destination file
every 3.minute do
  begin
    runner "Batch::DataReset.data_reset"
  rescue => e
    Rails.logger.error("aborted rails runner")
    raise e
  end
" cron "In whenever, the contents described in config/schedule.rb are reflected in crontab.
Terminal
$ bundle exec whenever --update-crontab
If you see the following, you are successful
Terminal
[write] crontab file updated
crontab -l ➡︎ Check if it is actually reflected in crontab
If the following appears, it works
Terminal
# Begin Whenever generated tasks for: /home/vagrant/work/app name/config/schedule.rb at: 2020-05-05 03:29:06 +0000
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /bin/bash -l -c 'cd /home/vagrant/work/app name&& bundle exec bin/rails runner -e [Development environment] '\''Batch::DataReset.data_reset'\'' >> log/cron.log 2>&1'
# End Whenever generated tasks for: /home/vagrant/work/app name/config/schedule.rb at: 2020-05-05 03:29:06 +0000
$ sudo systemctl start crond ➡︎ cron start
$ sudo systemctl stop crond ➡︎ Stop cron
$ bundle exec whenever --clear-crontab ➡︎ Remove cron
Recommended Posts