Java 如何安排任务运行一次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34324082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I schedule a task to run once?
提问by azurefrog
I want to delay doing something, along the lines of setting a countdown timer that will "do a thing" after a certain amount of time.
我想延迟做某事,就像设置一个倒数计时器,它会在一定时间后“做一件事”。
I want the rest of my program to keep running while I wait, so I tried making my own Threadthat contained a one-minute delay:
我希望我的程序的其余部分在我等待时继续运行,所以我尝试制作自己的Thread包含一分钟延迟的程序:
public class Scratch {
private static boolean outOfTime = false;
public static void main(String[] args) {
Thread countdown = new Thread() {
@Override
public void run() {
try {
// wait a while
System.out.println("Starting one-minute countdown now...");
Thread.sleep(60 * 1000);
// do the thing
outOfTime = true;
System.out.println("Out of time!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
countdown.start();
while (!outOfTime) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
While this worked, more-or-less, it seemed like there should be a better way of doing this.
虽然这或多或少有效,但似乎应该有更好的方法来做到这一点。
After some searching, I found a bunch of questions like these but they don't really address what I'm trying to do:
经过一番搜索,我发现了一堆这样的问题,但它们并没有真正解决我想要做的事情:
- How do I schedule a task to run at periodic intervals?
- How i can run my TimerTask everyday 2 PM
- How to run certain task every day at a particular time using ScheduledExecutorService?
- Java execute task with a number of retries and a timeout
I don't need anything this complicated; I just want to do a single thing after a certain amount of time while letting the rest of the program still run.
我不需要这么复杂的东西;我只想在一段时间后做一件事,同时让程序的其余部分仍然运行。
How should I go about scheduling a one-time task to "do a thing"?
我应该如何安排一次性任务来“做一件事”?
采纳答案by azurefrog
While the java.util.Timerused to be a good way to schedule future tasks, it is now preferable1to instead use the classes in the java.util.concurrentpackage.
虽然java.util.Timer过去是安排未来任务的好方法,但现在最好1代替使用java.util.concurrent包中的类。
There is a ScheduledExecutorServicethat is designed specifically to run a command after a delay (or to execute them periodically, but that's not relevant to this question).
有一个ScheduledExecutorService专门设计用于在延迟后运行命令(或定期执行它们,但这与此问题无关)。
It has a schedule(Runnable, long, TimeUnit)method that
它有一个schedule(Runnable, long, TimeUnit)方法
Creates and executes a one-shot action that becomes enabled after the given delay.
创建并执行在给定延迟后启用的一次性操作。
Using a ScheduledExecutorServiceyou could re-write your program like this:
使用 aScheduledExecutorService你可以像这样重写你的程序:
import java.util.concurrent.*;
public class Scratch {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
System.out.println("Starting one-minute countdown now...");
ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
@Override
public void run() {
// do the thing
System.out.println("Out of time!");
}}, 1, TimeUnit.MINUTES);
while (!countdown.isDone()) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
scheduler.shutdown();
}
}
One of the nice things you get by doing things this way is the ScheduledFuture<?>object you get back from calling schedule().
以这种方式做事的好处之一是ScheduledFuture<?>调用schedule().返回的对象。
This allows you to get rid of the extra booleanvariable, and just check directly whether the job has run.
这允许您摆脱额外的boolean变量,而只需直接检查作业是否已运行。
You can also cancel the scheduled task if you don't want to wait anymore by calling its cancel()method.
如果不想再等待,也可以通过调用其cancel()方法取消计划任务。
1See Java Timer vs ExecutorService?for reasons to avoid using a Timerin favor of an ExecutorService.
1参见Java Timer 与 ExecutorService?出于避免使用 aTimer支持a 的原因ExecutorService。
回答by Apeksha Saxena
Thanks it worked for me. I used scheduler to schedule a task at a batchinterval calculated at runtime.
谢谢它对我有用。我使用调度程序以运行时计算的批处理间隔调度任务。
manualTriggerBatchJob.setSchedulingProperties(pblId, batchInterval);
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);
@SuppressWarnings("unchecked")
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(manualTriggerBatchJob,
batchIntervalInMin,TimeUnit.MILLISECONDS);

