SOAP, Background Tasks, and AJAX
Recently in Rails I’ve been interacting with various SOAP services and running them in the background with Workling. I needed to relay the SOAP response to the client’s web browser, so I decided to use AJAX to poll the status of my background tasks.
This is great if you have < 30 second background tasks running, but don’t want to block a user (and a request).
I created a Rails plugin, called AjaxTask, that has two components:
- Methods to use in your controller to define a task handler and create tasks
GitHub Link: http://github.com/chrismoos/ajaxtask
The first thing to do is define the handler. This instructs the AjaxTask plugin to create a handler that will respond to ajax requests, as well as dispatch to your actual tasks. The only parameter to ajaxtask_handler is a symbol, which MUST be identical to a named route. This is how a URL gets from Rails to the plugin.
Now we will define a task:
This tells the plugin to respond to a task named mytask.
By doing this, we must implement two methods in our controller.
mytask_start is called when a browser starts a new task. You should probably fire off your background task in this method.
mytask_start should return a unique ID for the task. By using Workling and calling .async, a unique ID is returned.
The worker is the meat of our background task. In this we will do something that might take a while, and also update the status.
The important things to note here are what we set the return to. AjaxTask recognizes the following:
They should be pretty self explanatory. Now let’s see what the client side looks like.
Here is an example of what an HTML page that uses AjaxTask:
Looking at the above client code, you can see how easy it is to present a background task’s processing to a user.
That does it for now, I’ll try to document and post more soon abou AjaxTask.