LoginSignup
128
118

More than 5 years have passed since last update.

Railsのバッチ処理: whenever

Last updated at Posted at 2012-07-25

Railsでバッチ処理をするのにwheneverというgemを使用したのでまとめておきます。

導入

Gemfileに下記を追加します。

Gemfile
gem 'whenever', :require => false

bundle installします。

$ bundle install

設定ファイル

下記を実行します。

$ wheneverize .

そうすると、config/schedule.rbというファイルが生成されます。定期的に実行したいコマンドをこのファイルに記述していきます。

下記にサンプルを示します。

config/schedule.rb
set :output, 'log/cron.log'

every 3.hours do
  runner "MyModel.some_process"
  rake "my:rake:task"
  command "/usr/bin/my_great_command"
end

every 1.day, :at => '4:30 am' do
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  runner "SomeModel.ladeeda"
end

every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
  runner "Task.do_something_great"
end

every '0 0 27-31 * *' do
  command "echo 'you can use raw cron syntax too'"
end

runnerやrakeで実行するコマンドや、commandでシェルスクリプトやアプリケーションを実行することもできます。

また、outputを指定することで出力するファイルを指定することができます。

設定した内容の確認

whenenverコマンドを実行することで、実際にcronに登録する内容を確認することができます。

$ whenever
0 * * * * /bin/bash -l -c 'cd /home/hirotaka/workplace/rails-project && script/rails runner -e production '\''SomeModel.ladeeda'\'' >> log/cron.log 2>&1'

0 0,3,6,9,12,15,18,21 * * * /bin/bash -l -c 'cd /home/hirotaka/workplace/rails-project && script/rails runner -e production '\''MyModel.some_process'\'' >> log/cron.log 2>&1'

0 0,3,6,9,12,15,18,21 * * * /bin/bash -l -c 'cd /home/hirotaka/worksplace/rails-project && RAILS_ENV=production bundle exec rake my:rake:task --silent >> log/cron.log 2>&1'

0 0,3,6,9,12,15,18,21 * * * /bin/bash -l -c '/usr/bin/my_great_command >> log/cron.log 2>&1'

30 4 * * * /bin/bash -l -c 'cd /home/hirotaka/workplace/rails-project && script/rails runner -e production '\''MyModel.task_to_run_at_four_thirty_in_the_morning'\'' >> log/cron.log 2>&1'

0 12 * * 0 /bin/bash -l -c 'cd /home/hirotaka/worksplace/rails-project && script/rails runner -e production '\''Task.do_something_great'\'' >> log/cron.log 2>&1'

0 0 27-31 * * /bin/bash -l -c 'echo '\''you can use raw cron syntax too'\'' >> log/cron.log 2>&1'

## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated.
## [message] Run `whenever --help' for more options.

Capistranoでのデプロイ

本番環境に反映するには、Capistranoのレシピを使用します。

deploy.rbを編集して、以下をロールを定義している下あたりに追加します。

config/deploy.rb
set :whenever_command, "bundle exec whenever"
require "whenever/capistrano"

これでcap deployすればconfig/schedule.rbの内容がcrontabに反映されるようになります。

まとめ

whenenverを使えば、バッチ類がschedule.rbにまとまっていて、どういったバッチがどういう周期でまわっているのか一目瞭然なのでいいですね。

いままで、手動でcrontabに書いたので、このあたりがcapistranoで反映ができるのも便利です。

128
118
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
128
118