akishin999の日記

調べた事などを書いて行きます。

Rails でバッチ処理

色々な方法があるみたいですが、Rails の仕組みをそのまま利用できるので、以下のような構成に落ち着きました。


まず、バッチスクリプトを配置するためのディレクトリ(ここでは #{RAILS_ROOT}/app/batches )を作成します。

exampleapp
  ├─app
  │  ├─controllers
  │  ├─helpers
  │  ├─models
  │  ├─views
  │  └─batches  <= batches ディレクトリを作成し、その下にファイルを格納する
  │      └─foo
  │          └─bar.rb
  ├─config
  ├─db
  ├─lib
  ├─log
  ├─public
  ├─script
  ├─test
  ├─tmp
  └─vendor


追加したディレクトリを lib ディレクトリなどと同様、Rails に自動的に読み込んでもらうには、config/environment.rb に以下の設定を追加します。

# Add additional load paths for your own custom dirs
config.load_paths += %W( #{RAILS_ROOT}/app/batches )


試しに動かしたサンプルコードは以下のようなもの。

  • #{RAILS_ROOT}/app/batches/foo/bar.rb
module Foo
  class Bar
    def self.execute
      p 'Hello, World.'
    end
  end
end


以下のように script/runner から実行します。

 >ruby script/runner Foo::Bar.execute
  #=> "Hello, World."


この処理を cron で定期的に実行する場合は、以下のような感じで設定します。

 */10 * * * * /usr/bin/ruby /home/foo/example/current/script/runner -e production Foo::Bar.execute


今の所これで問題無く動作しています。