【发布时间】:2013-10-28 10:40:39
【问题描述】:
类中的非静态方法发送一个经常“挂起”的 HTTP 获取请求(永远等待响应);为了在一定的超时后切断它,我使用Timer,如this SO question所示。
每次调用方法并启动get时,我希望计时器从头开始。
但事实并非如此;发生的情况是计时器在第一次调用该方法时启动,并在整个程序执行期间继续运行;当它超时时,它会中止当前正在运行的任何获取请求。
这是我的代码(简化):
public void processRequest() throws Exception {
final HttpClient client = HttpClientBuilder.create().build();
final String target = this.someString;
final int timeout = 10;
HttpGet get = new HttpGet(target);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
get.abort();
// if the request times out it probably means
// the server is down so we exit the program
// and don't run any more requests
System.exit(1);
}
catch (Exception e) {
// warn that something went wrong
}
}
}, timeout * 1000);
//Execute and get the response
final HttpResponse response = client.execute(get);
final int code = response.getStatusLine().getStatusCode();
if (code == 200) {
// do something with the response, etc.
}
}
processRequest 为它所属的类的每个实例调用一次;第一次调用后,程序在timeout 的持续时间后退出。
编辑:或者它可能是第一个继续运行的计时器,我需要在收到 get 响应时终止它?
Edit2:好的,解决了它:在收到响应时添加timer.cancel() 可以避免问题。但我不明白为什么! get 相对于一个实例;来自前一个实例的计时器如何中止属于另一个实例的获取?
【问题讨论】:
-
System.exit(1);将拒绝您的整个申请。
-
是的,这就是我们想要的;如果我们对任何请求都有超时,这几乎可以肯定意味着服务器已关闭。所以我们不想继续这个程序,因为这样做会向停机的服务器发送更多请求。我们需要找人来恢复服务器。
-
你有没有在你想要的响应之后取消计时器?
-
使用“ArrayBlockingQueue
-
@rcook,不,那是我的问题! ;-) 但是目前还不清楚来自给定实例的计时器如何终止来自另一个实例的请求。