10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

外部連携等が遅い場合に強制的にタイムアウトさせる方法

Last updated at Posted at 2013-01-17

rubyのtimeoutを用いる

sample_controller.rb
require 'timeout'

# ...
def index
  # 3秒たってもデータが取れなければ、Timeout::Errorがraiseされる
  Timeout::timeout(3) do
    # データ取りに行く
  end
rescue Timeout::Error
  render text: 'XXXサーバが遅いみたい'
end
# ...

まぁAjax使えよという内容。

Resqueとか?

resqueからのコピペ
class Archive
  require 'timeout'
  @queue = :file_serve

  def self.perform(repo_id, branch = 'master')
    repo = Repository.find(repo_id)
    # このJobがやりたいこととtransaction doは関係ないけど
    ActiveRecord::Base.transaction do
      Timeout::timeout(3) do
        repo.create_archive(branch)
      end
    end
  end
end

see: http://doc.ruby-lang.org/ja/1.9.3/class/Timeout.html

以下妄想

書いていて、こんな感じにできればワーカーの起動で面倒なことしなくて済みそうと思った。
(あるのかな?)

archive.rb
class Archive
  @queue = :file_serve
  @min_timeout = 5

  def self.perform(repo_id, branch = 'master')
    repo = Repository.find(repo_id)
    # Resque.current_worker.timeout でワーカーのタイムアウトが取ってこれる
    Timeout::timeout(Resque.current_worker.timeout) do
      # something
    end
  end
end

俺は5秒までのJob(@min_timeout <= 5)しか処理しないぜのワーカー

TIMEOUT=5 QUEUE=* rake resque:work

おいらは3秒までのJob(@min_timeout <= 3)しか処理しないぜのワーカー(ArchiveのキューはSkip)

TIMEOUT=3 QUEUE=* rake resque:work

と妄想。

10
12
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
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?