如何不执行超过预定时间的作业

How to not execute jobs which are past their scheduled time

我观察到通常安排在午夜的作业(但由于服务器进入节能模式而无法执行)在服务器退出节能模式后执行。这会导致意外的执行时间。

有没有办法告诉 Quartz 在任务远远落后于目标时间后不要执行任务?

是的。你只需要告诉 Quartz 如何处理 job misfires:

Another important property of a Trigger is its “misfire instruction”. A misfire occurs if a persistent trigger “misses” its firing time because of the scheduler being shutdown, or because there are no available threads in Quartz’s thread pool for executing the job. The different trigger types have different misfire instructions available to them. By default they use a ‘smart policy’ instruction - which has dynamic behavior based on trigger type and configuration. When the scheduler starts, it searches for any persistent triggers that have misfired, and it then updates each of them based on their individually configured misfire instructions. When you start using Quartz in your own projects, you should make yourself familiar with the misfire instructions that are defined on the given trigger types, and explained in their JavaDoc.

具体的 misfire 指令取决于您使用的 Trigger 类型。对于日常工作可能是这样的:

trigger = newTrigger()
        .withIdentity("trigger1", "group1")
        .withSchedule(dailyAtHourAndMinute(0,0)
                .withMisfireHandlingInstructionDoNothing()) // set misfire instruction
        .build();

但同样,这取决于触发器的类型。只需使用您的 IDE 查看可用的 withMisfire*() 方法,然后使用 withMisfireHandlingInstructionDoNothingwithMisfireHandlingInstructionNextWithRemainingCount (两者都会忽略错过的执行并等待下一个预定的执行)。

当我必须了解不同类型的 misfire 指令时,除了 Quartz 的教程和 API 文档外,我还使用了 this blog entry