I am trying to add a retry logic to a step in java. Using timers, I am able to repeat this step after certain time. However, in case the step doesn't get executed successfully, timer waits till the execution stops. My requirement is that I need to stop execution of this step after say 30s and then retry this logic.
Below is what I am trying to do.
Description of the step: I will call method processRequest by providing a Json input. This step gets executed successfully Everytime and returns a job Id. I am polling a url to get response to the provided job Id. This step sometimes doesn't get executed successfully or takes lot of time to return response. I want to terminate this task of polling and retry to call processRequest again which generates a new job Id and this has to be sent for polling. This logic has to get executed 5 times after waiting for 30s.
Json request={operation:resize};
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID;
Can I do this without extending my class to Thread class or please suggest if there's anything else to achieve the same.
I am looking for something like this:
String response="";
Int count=5;
While (count>0)
{
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID; // terminate step after 30s
If response !="";
Return response; // return response and stop the while loop.
}
One possible way is to use Thread.sleep()
. Assuming that you don't mind locking up your program for 30 seconds, you can do the following:
String response="";
int count=5;
While (count>0) {
String JOBID=processRequest(request);
String response=http://pollingUrl/JOBID;
if (!response.equals("")) {
return response; // return response and stop the while loop.
}
try {
Thread.sleep(6000); // 6 seconds
} catch (InterruptedException ie) {}
count--;
}
Note that the above won't work unless the http polling call is non-blocking. That is, if it waits internally until a response is provided, it won't work. But usually when polling calls are done there should be a mechanism to timeout at some point.
EDIT: I changed two things. I moved the sleep after the test for a response. And I modified how you were testing for equality (which may have been part of the problem). Use equals
and not ==
or !=
for comparing Strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.