【问题标题】:error when using cronTrigger with an expression that contains a year value将 cronTrigger 与包含年份值的表达式一起使用时出错
【发布时间】:2012-05-18 11:40:04
【问题描述】:

我观察到使用包含年份值的 CronTrigger 在 Quartz 中调度作业的奇怪行为。

以下是我创建触发器并使用它安排作业的方式:

CronTrigger trigger =  cronJobTriggerFactory.getObject();
trigger.setName(triggerName);
trigger.setGroup(triggerGroupName);
trigger.setCronExpression(cronSchedule);
trigger.setVolatility(false);

JobDetail job = schedulableJobFactory.getObject();
job.setName(jobName);
job.setGroup(jobGroupName);
job.setVolatility(false);
job.setDurability(true);
Date scheduleTime1 = scheduler.scheduleJob(job, trigger);
logger.info(job.getKey() + " will run at: " + scheduleTime1);

然后在我的单元测试中,我确定“现在”日期,将其添加 5 分钟,计算此日期/时间的 cron 表达式,并使用此时间表调用我的主要课程安排作业。这是单元测试的输出,显示通过了哪个 cron 表达式:

NotificationSchedulerTest - Today is: 9 May 2012 05:32 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 05:37 PM
NotificationSchedulerTest - cron schedule is: 0 37 17 * 4 ? 2012

但是,当尝试使用此 cron 表达式安排作业时 - 我收到以下错误:

org.quartz.SchedulerException: Based on configured schedule, the given trigger will never fire.

如您所见,相对于我正在运行测试的日期/时间而言,日期是未来的日期...因此,尝试将作业安排在过去的某个时间运行应该不是问题.

现在下一个奇怪的事情:注意我确实在我的 cron 表达式中指定了年份值:“0 37 17 * 4 ? 2012”。

如果我修改 cron 表达式的生成并将年份字段保留为未指定(因为它是可选的):“ 0 37 17 * 4 ?” 然后调度确实成功了,但是,调度程序显示下一次触发作业是在 2013 年! (一年后...... - 当然我不能等待那么久来验证它被解雇......):

NotificationSchedulerTest - Today is: 9 May 2012 06:11 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 06:16 PM
NotificationSchedulerTest - cron schedule is: 0 16 18 * 4 ?
...
NotificationScheduler - myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013

我在这些 cron 表达式中遗漏了什么吗?

【问题讨论】:

    标签: java cron quartz-scheduler crontrigger


    【解决方案1】:

    cron 表达式中的月份是从 1 开始的。这就是为什么永远不会执行0 37 17 * 4 ? 2012 的原因:今天是 5 月 10 日,您希望它在 4 月的每一天运行。当您删除年份时,它会在 2013 年打印下一个预定日期,但在 4 月! myJobKey 将在以下时间运行:Mon Apr 01 18:16:00 EDT 2013

    显然你的表达方式应该是:

    0 37 17 * 5 ? 2012
    

    或为了避免将来混淆:

    0 37 17 * May ? 2012
    

    【讨论】:

    • 谢谢!我知道这是一些愚蠢的事情......混乱来自我生成 cron 计划的方式 - 直接来自 Java Calendar 实例:'code'Calendar cal1 = Calendar.getInstance(); ... cronString.add(" " + String.valueOf(cal1.get(Calendar.MONTH));'code' 在日历月份从 0 开始!现在我必须为 Quartz 添加 1。非常感谢,托马斯!:)
    • 我犯了同样的错误。感谢这个答案,这是一个快速的发现。
    • 你好@Tomasz,我有 ONCE 类型的 0 48 15 10 1 ? 2020,它在 2020 年 1 月第 10 天 下午 15:48:00 触发。您能否建议我在这里做错了什么,因为我收到了同样的信息
    猜你喜欢
    • 2013-10-24
    • 2019-05-30
    • 1970-01-01
    • 2015-11-21
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多