job の基本メソッドを提供
resque 用 job クラスの基底クラスに include する
resque-status も include される
resque 2.0 には対応していない
Redis::Lock により、ロックしつつメソッドを呼び出す
Add this line to your application's Gemfile:
gem 'ans-job'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ans-job
# config/initializers/resque-status.rb
require "resque/status"
Resque::Plugins::Status::Hash.expire_in = 24.hours # 24hrs in seconds
Ans::Job.configure do |config|
config.lock_namespace = Resque.redis.namespace
end
# app/jobs/application_job.rb
class ApplicationJob
include Ans::Job
def on_failure(e)
puts e.message
# 実際はメールを送信、等の処理を行う
#ExceptionNotifier::Notifier.background_exception_notification(e).deliver
end
end
class MyJob < ApplicationJob
def perform_with_lock
total = 10
total.times do |current|
# resque-status の進捗設定メソッド
at current, total, "progress: #{current}/#{total}"
end
raise "runtime error" # => 例外は on_failure で処理
end
end
class MyJobNoLock < ApplicationJob
def perform_without_lock
raise "runtime error"
end
end
MyJob.perform # => puts "runtime error"
MyJobNoLock.perform # => puts "runtime error"
resque-status の進捗メソッドを使用すると、 resque 管理画面でパーセント表示が進む
呼び出さなくても完了したかどうかはわかるので、パーセント表示が見たい場合以外はやらなくても問題ない
- Ans::Job を include すると、 Resque::Plugins::Status が include される
initialize,perform,on_success,self.performメソッドは定義しないようにperform_with_lockメソッドを定義するとロックしつつ作業を行う
タイムアウト秒はlock_timeoutメソッドを定義することでオーバーライドできる- ロックを望まない場合、
perform_without_lockメソッドを定義する
perform_with_lockとperform_without_lockの両方を定義した場合、perform_without_lockが優先され、perform_with_lockは呼び出されない remove_on_success?が true を返す場合、完了時にステータスが削除される
class MyJob < ApplicationJob
def lock_timeout
0.1 # Redis::Lock のタイムアウト秒
end
def remove_on_success?
false # 成功時にステータスを削除する場合は true を返す
end
def lock_key_suffix
"" # lock_key に追加する文字列
# 複数のホストで worker を走らせる場合、ホスト名的なものを追加することでロックが頻発するのを防ぐ
# デフォルトでそうしないのは、複数のホストで実行したくない場合はロックされてほしいから
# 複数のホストで実行することを想定している場合、ここでホスト名を返す
end
end
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request