views:

106

answers:

5

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.

A: 

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.

Andre
I should have mentioned that you'd want to of course save the time as which point TimerTask starts, so that after five minutes you can kill it if your exit condition doesn't end it first.
Andre
+4  A: 

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

tim_yates
The JavaDoc say that `shutdown` -- Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. -- The running thread will not return immediately... are you thinking of `shutdownNow()`?
tim_yates
Good point - I'll delete that comment.
Adamski
thank you :)Good Answer
Zakaria
A: 

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.

gimenete
+2  A: 

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

http://stackoverflow.com/questions/1247390/java-native-process-timeout/1249984#1249984

ZZ Coder
A: 

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.

Oak