LoginSignup
15
14

More than 5 years have passed since last update.

[Rails]wheneverを使って特定時間に集中しがちなバッチ処理を分散させる

Posted at

毎日夜中にバッチ処理回したい時ってあるじゃないですか。しかも何も考えずに設定すると、気づいたら夜の4:00とかにタスクが集中してサーバの負荷が高くなる事もしばしば。

Railsでバッチ処理を実現するならwheneverが便利ですが、wheneverを使うと以下のように例えば4時頃に実行したいタスクを10分ずつずらして実行できます。

# だいたい4時頃実行すればいいタスク
tasks = %w(task1 task2 task3 task4)
tasks.each_with_index do |task, i|
  exec_time = ( Time.parse("4:00") + i*10.minutes ).strftime("%H:%M")
  every 1.day, at: exec_time do
    rake task
  end
end

出力結果は下記。

0 4 * * * /bin/bash -l -c 'cd /path/to/app && RAILS_ENV=production bundle exec rake task1 --silent >> log/cron.log 2>> log/whenever.log'

10 4 * * * /bin/bash -l -c 'cd /path/to/app && RAILS_ENV=production bundle exec rake task2 --silent >> log/cron.log 2>> log/whenever.log'

20 4 * * * /bin/bash -l -c 'cd /path/to/app && RAILS_ENV=production bundle exec rake task3 --silent >> log/cron.log 2>> log/whenever.log'

30 4 * * * /bin/bash -l -c 'cd /path/to/app && RAILS_ENV=production bundle exec rake task4 --silent >> log/cron.log 2>> log/whenever.log'

きれいに10分ずつずれて実行されてます。
rubyって便利ですね!

15
14
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
15
14