Zakaria
Zakaria

Reputation: 1715

How to execute task for a specific period in Java.?

In fact I would execute a specific task( a set of instructions) for a determined period.

For example : I want my program to execute the task for 5 minutes, if it gets the right result it stops , else it will continue executing normal task for the 5 minutes and in the end it tells me.

How can I implement this in Java.

Upvotes: 4

Views: 2758

Answers (5)

Oak
Oak

Reputation: 26868

Using a future are a very simple way, in my opinion:

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> f = executorService.submit(myTask);
try {
    f.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    f.cancel(true);
}

But of course, the created thread need to be able to handle interrupts.

Upvotes: 0

tim_yates
tim_yates

Reputation: 171074

You could something like the following:

import java.util.concurrent.* ;

ExecutorService svc = Executors.newFixedThreadPool( 1 ) ;
svc.submit( new Runnable() {
  public void run() {
    // Do long running task
  }
} ) ;
svc.shutdown() ;
svc.awaitTermination( 300, TimeUnit.SECONDS ) ;

Javadocs for ExecutorService are here

[edit]

I should probably note however that depending on what your long running task is doing, it may not be possible to force it to stop running

[edit2] the submit method returns a Future object, which you can then call get on with a timeout. This get call will block until a result is ready, or if the timeout is reached throw a TimeoutException. In this way, you can get a result back from your long running task if that is what you wanted

Upvotes: 4

ZZ Coder
ZZ Coder

Reputation: 75456

The most robust approach is to use FutureTask with a thread pool. See my answer to this question,

java native Process timeout

Upvotes: 2

gimenete
gimenete

Reputation: 2669

Since Java 1.5 there is a high level API for concurrency. It includes a set of interfaces called Executors. They may can help you.

Upvotes: 0

Andre
Andre

Reputation: 1641

You'd probably want to use a combination of Timer and TimerTask. Create a new Timer and call the schedule(TimerTask, long, long) method to start it. Your TimerTask object would be the item responsible for checking for your exit condition.

Upvotes: 0

Related Questions