java.lang.RuntimeException: CronExpression '4 27 11 ? 8 ? 2014' is invalid,

…衆ロ難τιáo~ 提交于 2019-12-06 11:24:22

'?' in a cron expression is meant to allow day-of-month and day-of-week to not interfere with each other (e.g., so you can specify a cron to trigger on any Friday regardless of the day of the month or on the 13th of every month, regardless of which day it is). If you specify both of them to be '?' you don't have any date specification, which would be illegal.

A cron expression for the current date would use the day of the month, and ignore the day of the week. E.g., for today, September 15th, 2014, you'd specify 4 27 11 15 9 ? 2014.

This can be generated by extracting the current day from the java Date object:

public static void main(String[] args) {
    Date date = new Date();
    String formatted_date = generateCronExpression
                             (Integer.toString(date.getSeconds()),
                              Integer.toString(date.getMinutes()),
                              Integer.toString(date.getHours()),
                              Integer.toString(date.getDate()),
                              Integer.toString(date.getMonth() + 1), // see Note #2
                              "?",
                              Integer.toString(date.getYear() + 1900));
}

Notes:

  1. Date.getDate(), Date.getHours() etc. are deprecated - you should use Calendar.get instead. I kept the current code from the OP in order to make the solution clear and not to add clutter with extra details.
  2. Date.getMonth() (and the new recommended method, Calendar.get(Calendar.MONTH)) return a zero-based representation of the month (e.g., January is 0, February is 1, etc.), while cron expressions are one based (e.g., January is 1, February is 2, etc) - so you should add 1 for the cron-expression.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!