LoginSignup
3
4

More than 1 year has passed since last update.

【Ruby on Rails】EC2でwheneverを使ってcrontabを設定する時のハマったことの解決

Last updated at Posted at 2021-01-16

wheneverというのはRuby on Railsのgemであり、crontabを設定する時によく使われています。

使い方

使い方はGithubホームページに詳しく記載されていますが、主に使うのは下記になります。

Gemfileに追加

Gemfile
gem 'whenever', require: false

インストール

bundle exec wheneverize .

schedule.rbファイルの内容を確認する

whenever

開発環境でcrontabを更新する

whenever --update-crontab --set environment='development'

Capistranoに入れる

config/deploy.rb
set :whenever_roles, -> { :app }
Capfile
require 'whenever/capistrano'

ハマったことなどの解決

EC2では動かない

EC2にデプロイの後、crontabが動かず、ログ確認したらBundleバージョンが間違いなどの問題

job_typeを以下に設定すれば良い

config/schedule.rb
set :output, environment == 'development' ? 'log/crontab.log' : '/deploy/apps/<アプリ名/shared/log/crontab.log'
job_type :rake, 'export PATH="$HOME/.rbenv/bin:$PATH"; eval "$(rbenv init -)"; cd :path && RAILS_ENV=:environment bundle exec rake :task :output'

時間通りに動かない

タイムゾーンが間違い可能性が高いです。

タイムゾーン設定方法は:

config/schedule.rb
require 'active_support'
require 'active_support/core_ext/time'

def jst(time)
  Time.zone = 'Asia/Tokyo'
  Time.zone.parse(time).localtime($system_utc_offset)
end

every 1.day, at: jst('6:00 am') do # 日本時間毎朝6時に実行
  rake 'example:task'
end

crontabのログにExecJS::RuntimeUnavailable エラーが出たとき

Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

Gemfileにmini_racerを追加すればいいです。therubyracerでも大丈夫ですが、Macにはインストールが難しいのでmini_racerを使います。

3
4
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
3
4