【Rails】Wheneverを使ってバックグラウンド処理をしたい
github
https://github.com/javan/whenever
Wheneverでできること
Railsでcronのバッチを作成して、以下の4つのコマンドを定期的に走らせることができる。
ターミナルでよく使うコマンド一覧
/config/schedule.rbを作成
$ wheneverize .
cronの設定の確認
$ bundle exec whenever
cronに処理を登録
$ bundle exec whenever --update-crontab
cronに登録した処理の削除
$ bundle exec whenever --clear-cron
手順
Gemfile
gem 'whenever', :require => false
ターミナル
$ wheneverize . > [add] writing `./config/schedule.rb' > [done] wheneverized!
/config/application.rb
lib/tasks/***.rbを読み込む場合、lib配下をロードするように設定する。
module xxx # railsアプリ名 class Application < Rails::Application config.autoload_paths += %W(#{config.root}/lib) config.autoload_paths += Dir["#{config.root}/lib/**/"] end end
/config/schedule.rb
# 実行環境の設定 set :environment, :development # 実行処理の内容 every 2.hours do command "/usr/bin/some_great_command" runner "MyModel.some_method" rake "some:great:rake:task" end every 4.days do runner "AnotherModel.prune_old_records" end