JAVA如果我把我的时间安排在每天中午12点之后,会发生什么



我正在使用以下代码来调度计时器(java.util.timer):

Timer mytimer = new Timer("My Timer");
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 12);
mytimer.schedule(mytask, c.getTime(), 24*60*60*1000);

我希望计时器任务每天中午12:00运行。我的问题是,如果应用程序在12:00之后运行,会发生什么。比方说16:00。计时器任务会在第二天12:00运行吗?

Timer类的文档说明了以下关于方法的信息公共无效计划(TimerTask任务、Date firstTime、long period)

在固定延迟执行中,每次执行都是相对于前一次执行的实际执行时间进行调度的。如果执行由于任何原因(如垃圾收集或其他后台活动)而延迟,则后续执行也将延迟。从长远来看,执行频率通常会略低于指定周期的倒数(假设Object.wait(long)的系统时钟是准确的)。因此,如果计划的第一次是在过去,则计划立即执行

因此,我们可以从上面了解到,任务将立即被安排和执行,之后根据您的程序,24小时后将再次执行。因此,如果是16:00,它将立即执行,并将在第二天16:00再次执行。

您可以考虑使用ScheduledThreadPoolExecutor作为

它实际上是一个更通用的替代品计时器/计时器任务组合(链接)

此外,Java8还提供了一些有用的工具来进行所需的时间计算。例如:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void schedule(Runnable command) {
    LocalDateTime currentTime = LocalDateTime.now();
    LocalDateTime executionDate = LocalDateTime.of(currentTime.getYear(), 
                                                   currentTime.getMonth(), 
                                                   currentTime.getDayOfMonth(), 
                                                   12, 0); // begin execution at 12:00 AM
    long initialDelay;
    if(currentTime.isAfter(executionDate)){
        // take the next day, if we passed the execution date
        initialDelay = currentTime.until(executionDate.plusDays(1), ChronoUnit.MILLIS);
    } else {
        initialDelay = currentTime.until(executionDate, ChronoUnit.MILLIS);
    }
    long delay = TimeUnit.HOURS.toMillis(24); // repeat after 24 hours
    ScheduledFuture<?> x = scheduler.scheduleWithFixedDelay(command, initialDelay, delay , TimeUnit.MILLISECONDS);
}

您可以给出晚上11:59的时间,然后您的问题就会得到解决。它调用是因为12:00 PM日期将更改,所以它将调用您的任务。因此将时间12:00 PM更改为11:59

我一直在寻找同一个问题的答案,并提出了一个可能的解决方案。请记住,我是一个完全的新手,这样做可能会犯下许多编程罪。

如果你的计时器正在运行,为什么不这样检查一个特定的时间:

if(date.compareTo("00:00:00") == 0){
    //TODO
}

相关内容

最新更新