毎日夜中にバッチ処理回したい時ってあるじゃないですか。しかも何も考えずに設定すると、気づいたら夜の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って便利ですね!