Setting timeout for open-uri

require 'open-uri'
require 'resolv-replace'
require 'timeout'
TIMEOUT = 3
begin
  timeout(TIMEOUT) do
    open(url) do |f|
      # Do something
    end
  end
rescue TimeoutError => e
  # Do something on timeout
rescue => e
  # Do something on other errors
end
  • Interrupt with timeout is implemented by Ruby's Thread and it is not effective againt the process implemented by C, so DNS name resolution cannot be timeout. resolv-replace overwrites the methods to use Ruby's resolve library for DNS name resolution and enables timeout.
  • TimeoutError is not subclass of StandardError, so you have to catch TimeoutError explicitly.

Source: open-uriにtimeoutを設定する方法 | やむにやまれず