4

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.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
Zakaria
  • 1,675
  • 4
  • 21
  • 23

5 Answers5

4

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
  • 167,322
  • 27
  • 342
  • 338
  • 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 Jun 16 '10 at 14:28
2

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

java native Process timeout

Community
  • 1
  • 1
ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
0

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
  • 1,601
  • 3
  • 15
  • 15
  • 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 Jun 16 '10 at 14:10
0

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,649
  • 1
  • 20
  • 16
0

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
  • 26,231
  • 8
  • 93
  • 152