In Java, is it possible to execute a method for a certain period of time and stop after reaching the deadline?

I have this code that loads a webpage:

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 downloading, I tried to get the amount of downloaded data, and if it reaches the limit, I stopped loading, but I did not find a way to do this. If anyone knows how to do this, please tell me.

Now I want to limit the download time. Example: if the download passes after 20 seconds, I stop it. I want to do this because my program is a web browser, and if by mistake it starts downloading a large file, it will get stuck in the download, and I don’t want to do this, so the filter is loaded by size, but as I don’t know, filtering time will prevent this problem.

+3
5

:

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) {

        }

    }

}
+2

AOP @Timeable jcabi- ( ):

@Timeable(limit = 1, unit = TimeUnit.SECONDS)
String downloadContent() {
  if (Thread.currentThread.isInterrupted()) {
    throw new IllegalStateException("time out");
  }
  // download
}

, isInterrupted() , TRUE. Java.

, , : http://www.yegor256.com/2014/06/20/limit-method-execution-time.html

+2

java.util.Timer, . API.

+1

. , .

private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(20);
private String downloadContent() {
  connection.setConnectTimeout(TIMEOUT); /* Set connect timeout. */
  long start = System.nanoTime(); 
  final InputStream content;
  try {
    content = connection.getInputStream();
  } catch (IOException ex) { 
    return null;
  }
  /* Compute how much time we have left. */
  final long delay = TIMEOUT - 
    TimeUnit.NANOS.toMillis(System.nanoTime() - time); 
  if (delay < 1)
    return null;
  /* Start a thread that can close the stream asynchronously. */
  Thread killer = new Thread() {
    @Override
    public void run() {
      try {
        Thread.sleep(delay); /* Wait until time runs out or interrupted. */
      } catch (InterruptedException expected) { 
        Thread.currentThread().interrupt();
      }
      try {
        content.close();
      } catch (IOException ignore) {
        // Log this?
      }
    }
  };
  killer.start();
  try {
    String s = new Source(content).parser.toString();
    /* Task completed in time; clean up immediately. */
    killer.interrupt();
    return s;
  } catch (Exception e) {
    return null;
  }
}
+1

. :

1) Create a new stream and extract the contents from this stream. If the thread takes too long to respond, just go ahead and ignore its results. The downside of this approach: the background thread will load a large file.

2) Use a different HTTP connection API with many controls. I used the "Jakarta Commons HttpClient" a long time ago and was very pleased with my timeout opportunity.

0
source

All Articles