Ext-JS Tasks & Progressbars a match made in heaven
I’ve been working on some stuff that requires me to execute some long running tasks on a server from a web based client. I really wanted to a way to let the user know what was going on, and I figured a progress bar would be the best way to let them know what was going on and how much longer it was going to be before the task was complete.
Using Ext-JS this task was actually a lot easier then I had originally thought. Ext has these two great classes called TaskRunner and TaskManager. These classes basically allow you to create a task for execution in a multithreaded manner (we all know that JavaScript is only single threaded so this definitely will never be executed in parallel but we can all dream). Here’s an example from the Ext API on how to setup a task to run a simple clock that updates every second.
// Start a simple clock task that updates a div once per second var task = { run: function(){ Ext.fly('clock').update(new Date().format('g:i:s A')); }, interval: 1000; //1 second } var runner = new Ext.util.TaskRunner(); runner.start(task);
In my case I wanted to setup a task that would execute every 10 seconds and ask the server what the progress of my longrunning task was. I then used the information returned from the server to update the progress bar on page.
//Create the success handler for the Ajax request function successHandler (response, options) { if(response) { try { var json = Ext.util.JSON.decode(response.responseText); } catch (err) { return; } if (!json.done) { //update the progressBar by parsing the percentage updated //by the server and returned in the json response. percentage =json.results[0].strPercent; progressBar.updateProgress(json.results[0].percentage, 'Task ' + percentage + ' Complete'; } else { progressBar.updateProgress(1, 'Done'); } } var task = { run: function() { Ext.Ajax.request({ url: 'mystatus' success: successHandler, params: { processId: processId } }); }, interval 10000; //10 seconds } var runner = new Ext.util.TaskRunner(); runner.start(task);
Now I’ve let some code out here for handling the failure case of the Ajax request and a couple of other functions for handling what I’m actually doing on the server but you can start to see that with the combination of the TaskRunner and the ProgressBar adding “background” worker threads to your interface becomes a lot easier.
Unfortunately this solution is not necesarilly optimal since the client will constantly be polling the server asking what’s going on. A much better solution to this would be to implement a comet based service that allowed the server to merely report to the user its status and when it was complete.
Currently Ext does not have any comet handling functionality, but if you watch for my next post I’ll show how you can implement a comet based Servlet in Tomcat 6 and create a client that will listen for updates from the server.