2

How to wait for 2 minutes for method to complete, but if it does not complete then Exit and continue?

I want to wait for 2 minutes for method to complete, but if it does not complete in 2 minutes then Exit execution and continue ahead.

Pablo R. Mier
  • 719
  • 1
  • 7
  • 13
skool99
  • 780
  • 1
  • 16
  • 35

4 Answers4

6

Using the jcabi API has been pretty helpful for this kind of thing: jcabi API

Pretty slick annotation based API, so in your case it would work like this:

@Timeable(limit = 120, unit = TimeUnit.SECONDS)
public void methodYouWantToTime(){...}
Durandal
  • 5,575
  • 5
  • 35
  • 49
4

A combination of the following might work:

Time tracking:

// use this to record when a process started
long start = System.currentTimeMillis();
// subsequent calls can be used to track how long something has been running?
long timeInMillis = System.currentTimeMillis() - start;

Separate process:

java.lang.Thread // Extend this class
// And implement your own run() method.

In the loop that waits for the separate thread to finish, you could use:

Thread.interrupt(); // This method could then be used to stop the execution
Thread.stop(); // This is also another way to stop execution, but it is deprecated and its use is frowned upon!

HTH

Eric
  • 1,321
  • 2
  • 15
  • 30
4

With the help of Executor and Futures I think this could help

    ExecutorService executor = Executors.newCachedThreadPool();

    Future<String> future = executor.submit( new Callable<String>() {
        public String call() throws Exception {
            return someVeryLengthMethod();
        }});

    String result = null;
    try {
        result = future.get(2, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        // Somebody interrupted us
    } catch (ExecutionException e) {
        // Something went wring, handle it...
    } catch (TimeoutException e) {
        // Too long time
        future.cancel(true);
    }
    // Continue with what we have...

This will wait for the answer a specified time, and if the result is not available within that time the future is cancelled (which may or may not actually stop the execution of that task), and the code can continue.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
0

This question is explained in different threads. The best way is to use an ThreadPool with a timeout (see ExecutorService).

Example, submit a task and wait 60 seconds for the answer:

ExecutorService pool = Executors.newCachedThreadPool();
    Future<Object> future = pool.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            Thread.sleep(1000);
            return this;
        }
    });
    Object result = future.get(60, TimeUnit.SECONDS);

If you want to wait for the completion of a task but you are not expecting any output, better use:

pool.submit(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    // Wait until the task is completed, then shut down the pool
    pool.awaitTermination(60, TimeUnit.SECONDS);

More details in this thread: ExecutorService that interrupts tasks after a timeout

Community
  • 1
  • 1
Pablo R. Mier
  • 719
  • 1
  • 7
  • 13