code to ping websites works sometimes ...

Posted by trustfundbaby on Stack Overflow See other posts from Stack Overflow or by trustfundbaby
Published on 2010-04-20T05:46:50Z Indexed on 2010/04/20 5:53 UTC
Read the original article Hit count: 318

Filed under:
|
|

I'm testing out a piece of code to ping a bunch of websites I own on a regular basis, to make sure they're up.

I'm using rails and so far I have this hideous test action that I'm using to try it out (see below).
The problem though, is that sometimes it works, and other times it won't ... sometimes it runs through the code just fine, other times, it seems to completely ignore the begin/rescue block ...

a. I need help figuring out what the problem is b. And refactoring this to make it look respectable.

Your help is much appreciated.

require 'net/http'
require 'uri'

def ping
    @sites = NewsSource.all

    @sites.each do |site|
        if site.uri and !site.uri.empty?
            uri = URI.parse(site.uri)
            response = nil
            path = uri.path.blank? ? '/' : uri.path
            path = uri.query.blank? ? path : "#{path}?#{uri.query}"

            begin
                Net::HTTP.start(uri.host, uri.port) {|http|
                http.open_timeout = 30
                http.read_timeout = 30
                response = http.head(path)
                }

                if response.code.eql?('200') or response.code.eql?('301') or response.code.eql?('302')
                site.up = true
                else
                site.up = false
                end

                site.up_check_msg = response.message
                site.up_check_code = response.code
            rescue Errno::EBADF
            rescue Timeout::Error
                site.up = false
                site.up_check_msg = 'timeout'
                site.up_check_code = '408'
            end
            site.up_check_time = 0.seconds.ago
            site.save
        end
    end
end

© Stack Overflow or respective owner

Related posts about rails

Related posts about http