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

我怕爱的太早我们不能终老 提交于 2019-12-10 21:48:59

问题


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.


回答1:


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




回答2:


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

java native Process timeout




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/3053936/how-to-execute-task-for-a-specific-period-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!