简体   繁体   English

如何在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. 实际上,我会在一段确定的时间内执行特定任务(一组指令)。

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. 例如:我希望我的程序执行任务5分钟,如果它得到正确的结果它停止,否则它将继续执行5分钟的正常任务,最后它告诉我。

How can I implement this in Java. 我怎样才能在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 ExecutorService的 Javadocs就在这里

[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 . [edit2] submit方法返回一个Future对象,然后你可以通过超时调用get This get call will block until a result is ready, or if the timeout is reached throw a TimeoutException. get调用将阻塞,直到结果准备就绪,或者如果达到超时,则抛出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. 最强大的方法是将FutureTask与线程池一起使用。 See my answer to this question, 看看我对这个问题的回答,

java native Process timeout java native进程超时

You'd probably want to use a combination of Timer and TimerTask. 你可能想要使用Timer和TimerTask的组合。 Create a new Timer and call the schedule(TimerTask, long, long) method to start it. 创建一个新的Timer并调用schedule(TimerTask,long,long)方法来启动它。 Your TimerTask object would be the item responsible for checking for your exit condition. 您的TimerTask对象将是负责检查退出条件的项目。

Since Java 1.5 there is a high level API for concurrency. 从Java 1.5开始,有一个用于并发的高级API。 It includes a set of interfaces called Executors . 它包括一组名为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. 但是,当然,创建的线程需要能够处理中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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