概述
I have this code that downloads a web page:
HttpURLConnection connection;
private String downloadContent() {
InputStream content;
Source parser;
try {
content = connection.getInputStream(); //
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.
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 {
@Override
public String call() throws Exception {
// Do something
return "result";
}
}
public static void main(String[] args) {
Future 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一段时间执行一次,在Java中,是否可以执行一个方法一段时间并在达到时间限制后停止?...的全部内容,希望文章能够帮你解决java一段时间执行一次,在Java中,是否可以执行一个方法一段时间并在达到时间限制后停止?...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复