Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
283
Help us understand the problem. What is going on with this article?

More than 3 years have passed since last update.

@yumiyon

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

何ができるか

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に値が反映されます。

283
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
283
Help us understand the problem. What is going on with this article?