- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试每天早上 5 点运行某项任务。因此,我决定使用 ScheduledExecutorService 来实现此目的,但到目前为止我已经看到了一些示例,这些示例展示了如何每隔几分钟运行一次任务。
而且我找不到任何示例来说明如何每天在早上的特定时间(上午 5 点)运行任务,并考虑夏令时的事实 -
下面是我的代码,每 15 分钟运行一次 -
public class ScheduledTaskExample {
private final ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
public void startScheduleTask() {
/**
* not using the taskHandle returned here, but it can be used to cancel
* the task, or check if it's done (for recurring tasks, that's not
* going to be very useful)
*/
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
try {
getDataFromDatabase();
}catch(Exception ex) {
ex.printStackTrace(); //or loggger would be better
}
}
}, 0, 15, TimeUnit.MINUTES);
}
private void getDataFromDatabase() {
System.out.println("getting data...");
}
public static void main(String[] args) {
ScheduledTaskExample ste = new ScheduledTaskExample();
ste.startScheduleTask();
}
}
有没有什么办法,我可以使用 ScheduledExecutorService
安排任务在每天早上 5 点运行,同时考虑到夏令时的事实?
还有 TimerTask
更适合这个还是 ScheduledExecutorService
?
最佳答案
与当前的 java SE 8 版本一样,它具有出色的日期时间 API 和 java.time
这种计算可以更容易地完成,而不是使用 java.util.Calendar
和java.util.Date
.
现在作为根据您的用例安排任务的示例:
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initialDelay = duration.getSeconds();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new MyRunnableTask(),
initialDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
initialDelay
计算要求调度程序延迟 TimeUnit.SECONDS
中的执行。对于此用例,单位毫秒及以下的时差问题似乎可以忽略不计。但您仍然可以使用duration.toMillis()
和TimeUnit.MILLISECONDS
用于以毫秒为单位处理调度计算。
And also TimerTask is better for this or ScheduledExecutorService?
否: ScheduledExecutorService
看起来比TimerTask
更好。 StackOverflow has already an answer for you .
来自@PaddyD,
You still have the issue whereby you need to restart this twice a yearif you want it to run at the right local time. scheduleAtFixedRatewon't cut it unless you are happy with the same UTC time all year.
因为这是真的,而且 @PaddyD 已经给出了解决方法(+1),我提供了一个使用 Java8 日期时间 API 的工作示例 ScheduledExecutorService
。 Using daemon thread is dangerous
class MyTaskExecutor
{
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
MyTask myTask;
volatile boolean isStopIssued;
public MyTaskExecutor(MyTask myTask$)
{
myTask = myTask$;
}
public void startExecutionAt(int targetHour, int targetMin, int targetSec)
{
Runnable taskWrapper = new Runnable(){
@Override
public void run()
{
myTask.execute();
startExecutionAt(targetHour, targetMin, targetSec);
}
};
long delay = computeNextDelay(targetHour, targetMin, targetSec);
executorService.schedule(taskWrapper, delay, TimeUnit.SECONDS);
}
private long computeNextDelay(int targetHour, int targetMin, int targetSec)
{
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
if(zonedNow.compareTo(zonedNextTarget) > 0)
zonedNextTarget = zonedNextTarget.plusDays(1);
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
public void stop()
{
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) {
Logger.getLogger(MyTaskExecutor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
注意:
MyTask
是一个具有函数 execute
的接口(interface).ScheduledExecutorService
,始终使用awaitTermination
调用shutdown
后关于它:您的任务总是有可能被卡住/死锁,并且用户将永远等待。我之前用日历给出的例子只是我提到的一个想法,我避免了精确时间计算和夏令时问题。根据@PaddyD的提示更新了解决方案
关于java - 如何使用 ScheduledExecutorService 每天在特定时间运行特定任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209919/
这是情况,代码如下 用户填写 3 个字段并按“添加”按钮 => 创建一个 ToDoBean 并将其添加到 ToDoModel(扩展 AbstractTableModel) 并使用模型中 ToDoBea
Quarkus 有一个 https://quarkus.io/guides/scheduler来安排任务。但是,我想使用 ScheduledExecutorService .这在夸克中是允许的吗?例如
我有以下代码: ScheduledExecutorService scheduledExecutor; ..... ScheduledFuture result = scheduledExecutor
我需要实现一个计划执行程序服务,该服务每隔 x 秒运行一个线程。如果线程执行时间超过 y 秒,则应中断线程执行。我尝试使用 ScheduledExecutorService 来实现该解决方案,该服务具
我正在创建一个新线程来检查文件夹中是否有新文件,然后 hibernate 一段定义的时间。 我的首选是使用 ScheduledExecutorService,但是,我找不到任何文档来说明这是否需要等待
如何让 ScheduledExecutorService 在给定时间段内以给定时间速率执行任务? 然后下面的代码将使其以 1 秒的速率执行...但是我如何限制所有这些重复的总周期 service.sc
我意识到,如果在我的可运行对象的 run 方法内部(或没有,但应该与之相关)引发异常,我 future 的所有任务都将不会运行。 所以我的问题是:我如何从这样的异常中恢复(在哪里捕获它)? 我已经尝试
我正在使用预定执行程序服务 私有(private) ScheduledExecutorService 池 = new ScheduledThreadPoolExecutor(1); 以固定速率运行可运
ScheduledExecutorService ScheduledExecutorService 是在主线程还是后台线程上运行,我经历了 documentation here 但没有找到。 任何帮助
我有一个耳朵,将作为后端耳朵部署在多个服务器上。在那个耳朵中,我需要添加 ScheduledExecutorService 以在特定时间从数据库中获取一些记录并处理它们。但我只需要处理一次,而不是在将
我有 ScheduledExecutorService,我正在尝试更新内部数据但没有结果 public void myMethod(final String myString) { myExe
我目前遇到了 ScheduledExecutorService 执行速度快于给定时间范围的问题。 scheduleAtFixedRate声明后续执行可能会延迟,但不会等待给定的时间。 GrabPutT
我正在使用 ScheduledExecutorService.scheduleWithFixedDelay() 来安排线程的定期启动。它可以工作,但线程正在 ThreadStackTrace 中累积(
我有以下代码,每 20 分钟后调用一次任务,并且工作正常。现在,在此之上,我希望它仅在 0900 到 1800 之间工作 ScheduledExecutorService scheduler = Ex
我有一个特定的任务,必须定期执行,或者根据条件仅执行一次。我正在使用以下方法: Runnable r = new Runnable() { public void run()
我有一个 ScheduledExecutorService 来获取定期执行的任务: scheduler = Executors.newScheduledThreadPool( what size? )
以下代码是从 JMenuItem 的 ActionListener 调用的。它只是启动一个 jar 文件。 ScheduledExecutorService schedulerExecutor = E
我有两个每秒运行的执行器服务。但是当我在 run 方法中插入一行代码时,其中一个会停止运行。这是我的类(class): 游戏服务器: public class GameServer implement
提出此问题的动机我正在运行一个在非常昂贵的硬件上运行的大型产品。出于测试目的而关闭它是不可能的,也不可能在生产环境中放置一个坏的 jar。我需要尽可能确保几乎确保我不会弄乱生产环境。 在暂存设置上运行
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我是一名优秀的程序员,十分优秀!