Reputation:
I'd like to take the attitude that if my server-side is too slow, just throw an exception and send back a meaningful error message to the client. I am arbitrarily setting this time limit to 5 seconds and will tweak it as needed.
I see that App Engine has ApiProxy.getCurrentEnvironment().getRemainingMillis()
which gives us the number of milliseconds we have left before it throws a DeadlineExceedException
and times us out.
I'd like to do something similar, but imposing my own 5-second restriction over GAE's 60-second restriction (again, for right now doesn't matter if I pick 5-seconds or 40-seconds, as long as they are stricter than what GAE imposes). I'd like to write a server-side handler/servlet that starts a 5-second timer. If the request does not return inside that amount of time it throws an exception and returns to the client:
public class MyTimedServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Start 5-second timer
Timer timer = new Timer(5000);
try {
timer.start();
response = handleRequest(request);
}
catch(TimeException timerException) {
response = ResponseFactory.newTimeExceededResponse();
}
}
}
Unfortunately, I don't see anything in the GAE API that resembles the Timer
object that I'm looking for.
I'm already planning on making use of multihthreading every request via ThreadManager.currentRequestThreadFactory().newRequestThread(...)
, so I don't want to waste one of these (I only get 10 at a time!) threads to create a background "Timer Thread" unless I absolutely have to.
So I ask: does GAE have something like this out of the box, and if I have to roll my own, how do I go about doing so? Thanks in advance!
Upvotes: 2
Views: 457
Reputation: 6005
Any asynchronous task (that don't follow the normal flow) in your code involves a new thread execution, in this case this task is to count the time.
However you can use the classes Timer
& TimerTask
both of them included in the App-Engine JRE white list.
Example code: not tested just a guide.
public class YourServlet extends HttpServlet {
Timer timer;
HttpServletResponse response;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)...{
int seconds = 5;
timer = new Timer();
timer.schedule(new DeadLine(), seconds * 1000);
/* the rest of your code here */
}
class DeadLine extends TimerTask {
public void run() {
response.getWriter().print("Error: deadline reached.");
}
}
}
Read this article about job scheduling in Java, for more info.
Upvotes: 1