我是靠谱客的博主 无聊指甲油,最近开发中收集的这篇文章主要介绍java一段时间执行一次,在Java中,是否可以执行一个方法一段时间并在达到时间限制后停止?...,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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中,是否可以执行一个方法一段时间并在达到时间限制后停止?...所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部