views:

30

answers:

1

I have the following in a Rails controller:

def poll
  records = []
  start_time = Time.now.to_i

  while records.length == 0 do
    records = Something.uncached{Something.find(:all,
        :conditions => { :some_condition => false})}

    if records.length > 0
      break
    end

    sleep 1

    if Time.now.to_i - start_time >= 20
      break
    end
  end

  responseData = []

  records.each do |record|
    responseData << {
      'something' => record.some_value
    }

    # Flag message as received.
    record.some_condition = true
    record.save
  end

  render :text => responseData.to_json
end

and then I have Javascript performing an AJAX request. The request sits there for 20 seconds or until the controller method finds a record in the database, waiting. That works.

function poll() {
  $.ajax({
    url: '/my_controller/poll',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: 'time=' + new Date().getTime(),
    success: function(response) {
      // show response here
    },
    complete: function() {
      poll();
    },
    error: function() {
      alert('error');
      poll();
    }
  });
}

When I have 5 - 10 tabs open in my browser, my web application becomes super slow.

Is this to be expected? Or is there some obvious improvement(s) I can make?

+2  A: 

Well.. This is not the best approach.

Depending on what server solution you choose, you may have 1,2,.. x available server threads. (For example, when you run script/server, you only get one thread.) When you 'sleep', the server thread is blocked and can not server any other request. As the thread number is limited, other requests 'wait' for the running request to be completed.

You must implement the logic cient-side (in JS). You can pool the server for 10 times each second, or until a record is found.

A jQuery library that may do the trick is jQuery Timers.

Vlad Zloteanu