LoginSignup
289

More than 5 years have passed since last update.

Railsで定期的にバッチ回す「Whenever」

Last updated at Posted at 2014-12-19

何ができるか

Railsでcronのバッチを作成して、定期的に回すことができます。

公式リポジトリ

whenever

wheneverをインストール

Gemfile
gem 'whenever', :require => false
$ bundle install --path vendor/bundle

設定ファイルを作成

$ bundle exec wheneverize . 
    [add] writing `./config/schedule.rb'
    [done] wheneverized! 

config/schedule.rb に設定を記述します。

config/schedule.rb

require File.expand_path(File.dirname(__FILE__) + "/environment")
set :output, 'log/cron.log'

# 1分毎に回す
every 1.minute do
  command "echo 'mossmossmossmossmossmoss'"
end

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

cronに反映する際のコマンド

  • 設定の確認
$ bundle exec whenever 
$ bundle exec crontab -e
  • cronにデータを反映
$ bundle exec whenever --update-crontab 
  • cronからデータを削除
$ bundle exec whenever --clear-crontab

これで定期的にバッチを回せます。

CapistranoでWhenever

デプロイ時に、本番環境にもcronの値をセットしたい時は、Capistranoの設定ファイルに下記を追記します。

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

これで cap deploy を行なえば、デプロイ先のcrontabに値が反映されます。

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
289