如何在Java中执行特定时期的任务? [英] 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.
例如:我希望我的程序在5分钟内执行任务,如果得到正确的结果,它将停止运行,否则它将在5分钟内继续执行正常任务,最后告诉我.
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.
如何用Java实现呢?
How can I implement this in Java.
推荐答案
您可以执行以下操作:
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 ) ;
不过,我可能要注意,根据您长期运行的任务正在执行的操作,可能无法强制其停止运行
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] Submit方法返回一个Future
对象,然后您可以调用该对象get
[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
这篇关于如何在Java中执行特定时期的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!