wheneverでMySQLバックアップを定期実行する

MySQLバックアップ処理はrakeタスクでつくり、
javan/whenever · GitHubでcrontabの管理をすることにします。

1. 導入

Gemfileに以下を追記し、bundle installします。

gem 'whenever', :require => false

2. schedule.rbの作成

$ bundle exec wheneverize .
[add] writing `./config/schedule.rb'
[done] wheneverized!

3. Rakeタスク作成

lib/tasksに、dbbackup.rbを作成します。

require 'active_record'

namespace :db do
  desc "Dumps the database"
  task backup: [:environment, :load_config] do

    environment = Rails.env
    configuration = ActiveRecord::Base.configurations[environment]
    db_server = "localhost"
    db_esc_path = ENV['backup_path'] # ファイルのバックアップ先のパス
    timestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
    backup_file = "#{db_esc_path}/#{timestamp}.dump"

    cmd = nil
    cmd = "MYSQL_PWD=#{configuration['password']} mysqldump -h #{db_server} -u #{configuration['username']} #{configuration['database']} > #{backup_file}"

    puts cmd
    exec cmd
  end
end

作成したRakeタスクを実行できるように
config/application.rbに、以下を追記します。

config.autoload_paths += %W(#{Rails.root}/lib)

Rakeタスクを実行できるか確認します。

$ bundle exec rake db:backup RAILS_ENV=production backup_path=tmp/backups

4. schedule.rbの編集

schedule.rbを以下のように編集します。

set :output, "log/crontab.log"
set :environment, :production
env :PATH, ENV['PATH']

every 1.day, :at => '3:30 am' do
    backup_path = "tmp/backups"
    rake "db:backup backup_path=#{backup_path}"
end

5. crontab設定

  • 登録
$ bundle exec whenever --update-crontab
[write] crontab file updated
  • 確認
$ bundle exec whenever 
$ bundle exec crontab -e
  • 削除
$ bundle exec whenever --clear-crontab

参考

Rails - mysqldumpでダンプするrakeタスク - Qiita

http://opendeskdiary.blogspot.jp/2011_07_01_archive.html