Reputation: 85
Please find below my requirement.
Requirement : Poll a web service. Two crucial parameters of polling max_timeout, polling_interval are configured in properties file. Overall objective is to spend for a time of overall in obtaining the response. If we get the response with in max_timeout, we can return the response to client. Otherwise we will throw an error saying that the operation is unsuccessful.
Below is the code snippet I have written.
int maxTimeOut = 10;
int interval = 2;
int iterations = maxTimeOut/interval;
boolean success = false;
for (int i = 0; i < iterations; i++)
{
System.out.println("Number of iteration = " + i);
try
{
Thread.sleep(interval * 1000);
System.out.println("Waited for " + interval + " seconds");
success = getWSResponse(i);
System.out.println("CALL" + ((success) ? "SUCCESSFUL" : "FAIL"));
if(success) break;
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
//Send the success flag to client
Could you correct me if this is the proper implementation of polling. I am little bit concerned that this code assumes that webservice call returns in no time. If this takes 2-3 seconds (usually it does ), then we would be spending more than max_timeout overall for POLLING alone. How could we fix this. Is there any better approach than this.
Upvotes: 2
Views: 8887
Reputation: 6831
If polling just means that the webservice is up and running, in your poll code you can try to open a connection to the webservice (with connection timeout) .If you are successfully able to connect, this means the webservice is up.
HttpURLConnection connection = null;
URL url = new URL("URL");
connection = (HttpURLConnection) url.openConnection();
connection .setConnectTimeout(timeout);//specify the timeout and catch the IOexception
connection.connect();
EDIT
Alternatively, you can call the webservice using an executor (see java.util.concurrent.ExecutorService) in a task with timeout and can decide accordingly. Sample :
// Make the ws work a time-boxed task
final Future<Boolean> future= executor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// get ws result
return getWSResponse();
}
});
try {
boolean result = future.get(max_wait_time, TimeUnit.SECONDS);
} catch (TimeoutException te) {
throw e;
}
Upvotes: 1
Reputation: 2111
you can combine the use of a ScheduledExecutorService
with the HttpURLConnection
-Timeout to poll in a given delay - and abort the task if it takes any longer.
Upvotes: 2