3 日坊主日記
2008-08-05 [長年日記]
_ [Ruby] Net::HTTP#open_timeout の使い方
#!/usr/bin/ruby
require 'net/http'
Net::HTTP.start('www.example.com') do |http|
response = http.head('/heartbeat.txt')
p response
end
(ruby) Net::HTTP で接続に失敗すると
:!ruby heartbeat.rb
/usr/lib/ruby/1.8/net/http.rb:560:in `initialize': Connection timed out - connect(2) (Errno::ETIMEDOUT)
from /usr/lib/ruby/1.8/net/http.rb:560:in `open'
from /usr/lib/ruby/1.8/net/http.rb:560:in `connect'
from /usr/lib/ruby/1.8/timeout.rb:48:in `timeout'
from /usr/lib/ruby/1.8/timeout.rb:76:in `timeout'
from /usr/lib/ruby/1.8/net/http.rb:560:in `connect'
from /usr/lib/ruby/1.8/net/http.rb:553:in `do_start'
from /usr/lib/ruby/1.8/net/http.rb:542:in `start'
from /usr/lib/ruby/1.8/net/http.rb:440:in `start'
from heartbeat.rb:3
shell returned 1
となる。
Connection timed out - connect(2) が出るまでかなり待たされるので timeout を設定するわけだが
#!/usr/bin/ruby
require 'net/http'
Net::HTTP.start('www.example.com') do |http|
http.open_timeout = 10 # xxx: 間違い
http.read_timeout = 20
response = http.head('/heartbeat.txt')
p response
end
これは間違い。start() でこけてるのにその後ろで指定してもだめ。なので
#!/usr/bin/ruby
require 'net/http'
http = Net::HTTP.new('www.example.com')
http.open_timeout = 10
http.read_timeout = 20
http.start do
response = http.head('/heartbeat.txt')
p response
end
:!ruby heartbeat.rb
/usr/lib/ruby/1.8/timeout.rb:54:in `open': execution expired (Timeout::Error)
from /usr/lib/ruby/1.8/net/http.rb:560:in `connect'
from /usr/lib/ruby/1.8/timeout.rb:56:in `timeout'
from /usr/lib/ruby/1.8/timeout.rb:76:in `timeout'
from /usr/lib/ruby/1.8/net/http.rb:560:in `connect'
from /usr/lib/ruby/1.8/net/http.rb:553:in `do_start'
from /usr/lib/ruby/1.8/net/http.rb:542:in `start'
from heartbeat.rb:6
shell returned 1
これで ok。
[ツッコミを入れる]
[]
