LoginSignup
83
64

More than 5 years have passed since last update.

Wheneverで環境ごとにschedule内容を変更する

Last updated at Posted at 2015-05-14

Whenever、crontabが簡単に定義できるし、capistranoでデプロイすれば勝手に設定変更してくれるから非常に便利ですよね。手で記述ミスしてないか確認しながら変更していた日々にバイバイ。crontab -rに怯える日々よサラバ。

普通に使うには普通に使えるんですが、production環境とstaging環境でcrontabの内容を変えたいときに、検索して出てくるやり方だと上手いこといかなかったので、メモ。

前提

  • whenever v0.9.x
  • capistrano v3.2.x

capistranoの設定

Capfile
require 'whenever/capistrano' # 追加
config/deploy.rb
set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } # 追加
config/production.rb
set :whenever_roles, :batch # 対象ロール
set :whenever_environment, :production # 対象環境
config/staging.rb
set :whenever_roles, :batch # 対象ロール
set :whenever_environment, :staging # 対象環境

Wheneverの設定

@environmentに環境名が入ってくるので、それを使って単純に分岐させてやるだけです。

config/schedule.rb
# 出力先のログファイルの指定
set :output, 'log/crontab.log'

if @environment.to_sym == :production
  # 10分毎
  every '*/10 * * * *', :roles => [:batch] do
    runner "Tasks::Hoge.execute"
  end
end

if @environment.to_sym == :staging
  # 1時間毎
  every '0 * * * *', :roles => [:batch] do
    runner "Tasks::Hoge.execute"
  end
end

他の方のやり方だと、ENV['RAILS_ENV']に環境名が入るようにwhenever_commandを使って実行コマンド自体をカスタマイズしていましたが、僕の場合エラーになってしまうので上記のような対応をしました。

set :whenever_command, -> { ["RAILS_ENV=#{fetch(:stage)}", :bundle, :exec, :whenever] }

Wheneverの反映

Wheneverだけ実行したい場合は、下記のようにすればOK。

# 反映
$ BRANCH=staging bundle exec cap staging whenever:update_crontab

# 削除
$ BRANCH=staging bundle exec cap staging whenever:clear_crontab
83
64
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
83
64