Monday 9 April 2012

Javascript Server Heartbeat

Another snippet of code... I need a function that could check to see if a particular resource was responding in a timely manner.

So I put together a function that made an ajax call (home rolled no libraries as I wanted to keep it small) but that also ran  setTimeout()  so that could set the threshold I wanted for a response 100, 200, 500 2000 milliseconds etc rather than simply having to wait for the request to timeout or respond with an error code.

Either when the ajax returns or the timeout hits a callback is triggered and passed either the ajax response status (200 for good, 404 for not found etc) or a simple  null  value followed by the request object (if not null).

This code is called by a function that specifies a URL to hit, a timeout for getting a response and a callback to send the response to - In my code, the call back is set to update a global scope flag with the pulse value and then uses a timeout to kick the whole process off again in 30 seconds so the web page is not hammering the server.


// Server Heartbeat Checker

function heartbeat(url, ttl, callback) {
    // Confirms active connection to server by custom URL response
    //
    if (!url) {
        url = "http://www.yourwebsitehere.com/yourpage?someheartbeatcall";
        // Replace with specific server heartbeat location and query string for cache busting
    }
    if (!ttl) {
        ttl = 1000; // Custom timeout in milliseconds
        // Replace with specific server heartbeat location and query string for cache busting
    }
    // Create the Ajax object
    var ajaxRequest;
    try{
            ajaxRequest = new XMLHttpRequest();
    }
    catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){
                // Unable to create
                callback(null);
                return;
            }
        }
    }
    // Set flag so only one pulse is recorded
    var called = false;
    // Make ajax call
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            if (!called) {
                called = true;
                callback(ajaxRequest.status, ajaxRequest);
            }
        }
    }
    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null); 
    // Make ttl timeout call
    var ttlcatch = setTimeout(function(){
        if (!called) {
            called = true;
            callback(null);
        }
    }, ttl);
    return;
}




var foo = false;

heartbeat("http://www.google.com", 1000, function(pulse){foo = pulse; alert(pulse);} )


No comments:

Post a Comment