gpt4 book ai didi

java - 如何安排任务运行一次?

转载 作者:IT老高 更新时间:2023-10-28 20:46:54 25 4
gpt4 key购买 nike

我想推迟做某事,就像设置一个倒数计时器,它会在一定时间后“做某事”。

我希望我的程序的其余部分在我等待时继续运行,所以我尝试制作自己的 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();
}
}
}
}


虽然这或多或少有效,但似乎应该有更好的方法来做到这一点。

经过一番搜索,我发现了一堆这样的问题,但它们并没有真正解决我想要做的事情:

我不需要这么复杂的东西;我只想在一段时间后做一件事,同时让程序的其余部分仍然运行。

我应该如何安排一次性任务来“做一件事”?

最佳答案

虽然 java.util.Timer 曾经是安排 future 任务的好方法,现在最好1 改用 java.util.concurrent 中的类包。

有一个 ScheduledExecutorService 专门设计用于在延迟后运行命令(或定期执行它们,但这与这个问题无关)。

它有一个 schedule(Runnable, long, TimeUnit) 方法

Creates and executes a one-shot action that becomes enabled after the given delay.


使用 ScheduledExecutorService你可以像这样重写你的程序:

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();
}
}

您通过这种方式获得的好处之一是ScheduledFuture<?>您通过调用 schedule() 得到的对象.

这可以让您摆脱额外的 boolean变量,直接检查作业是否已经运行。

如果您不想再等待,也可以通过调用它的 cancel() 来取消计划任务。方法。


1Java Timer vs ExecutorService?出于避免使用 Timer 的原因赞成 ExecutorService .

关于java - 如何安排任务运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com