简体   繁体   中英

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.

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

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

java native Process timeout

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM