在Java中,是否可以在一段时间内执行方法并在达到时间限制后停止? [英] In Java, is it possible to execute a method for a period of time and stop after it reaches the time limit?
问题描述
我有下面的代码可以下载网页:
I have this code that downloads a web page:
HttpURLConnection connection;
private String downloadContent() {
InputStream content;
Source parser;
try {
content = connection.getInputStream(); //<--here is the download
parser = new Source(content);
content.close();
return parser.toString();
} catch (Exception e) {
return null;
}
}
在进行下载时,我尝试获取已下载数据的数量,如果达到限制,我将停止下载,但是我没有找到执行此操作的方法.如果有人知道该怎么做,请告诉我.
While doing the download, I tried to get the amount of downloaded data, and if it reaches a limit, I stop the downloading, but I not found a way to do this. If someone know how to do, please tell me.
现在,我想限制下载时间.示例:如果下载通过20秒,我将停止它.我要这样做是因为我的程序是一个网络爬虫,如果出现错误,它将开始下载一个大文件,它将卡在下载文件中,而不是我不想这样做,因此欢迎按大小过滤下载,但我不知道,过滤时间可以避免此问题.
Now I want to limit the download time. Example: if the download pass 20 seconds, I stop it. I want to do this because my program it's an webcrawler and if by an error, it begins downloading a big file, it will stuck in the download, and is not this I want to do, so a filter in download by size is welcome, but as I don't know, a filter time will prevent this problem.
推荐答案
实现此目标的正确方法如下:
The proper way to achieve this is the following:
public class TimeOut {
public static class MyJob implements Callable<String> {
@Override
public String call() throws Exception {
// Do something
return "result";
}
}
public static void main(String[] args) {
Future<String> control
= Executors.newSingleThreadExecutor().submit(new MyJob());
try {
String result = control.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// 5 seconds expired, we cancel the job !!!
control.cancel(true);
}
catch (InterruptedException ex) {
} catch (ExecutionException ex) {
}
}
}
这篇关于在Java中,是否可以在一段时间内执行方法并在达到时间限制后停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!