繁体   English   中英

JAVA 如果我每天在 12:00 PM 之后安排我的 timertask 会发生什么?

[英]JAVA What happen if I schedule my timertask everyday at 12:00 PM after that time?

我正在使用以下代码来安排计时器 (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 类的文档说明了以下方法public void schedule(TimerTask task, Date firstTime, long period)

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

所以从上面我们可以理解,任务会立即被调度执行,然后根据你的程序在24小时后再次执行。 因此,如果是 16:00,那么它将立即执行,并在第二天 16:00 再次执行。

您可能会考虑使用ScheduledThreadPoolExecutor ,因为

它实际上是 Timer/TimerTask 组合的更通用的替代品 (链接)

此外,Java 8 提供了一些有用的工具来进行所需的时间计算。 一个例子可能是:

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
}

暂无
暂无

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

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