Cron Expression is not working for last day of the month

后端 未结 5 775
小鲜肉
小鲜肉 2021-01-16 20:40

I want to schedule a task to run on last day of every month at 10:10 AM. The cron expression is 0 10 10 L * ?

Now the problem is CronSequenceGener

相关标签:
5条回答
  • 2021-01-16 20:49

    This Schedule runs on the last day of the month an 10:10AM:

    @Scheduled(cron = "0 10 10 28-31 * ?")
    public void doStuffOnLastDayOfMonth() {
        final Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
            // do your stuff
        }
    }
    
    0 讨论(0)
  • 2021-01-16 21:05

    The last day of the month is not supported by Spring. See CronSequenceGenerator's javadoc.

    0 讨论(0)
  • 2021-01-16 21:10

    There is another possible approach, depending on what you want to do:

    import org.apache.commons.lang3.time.DateUtils;
    
    @Scheduled(cron = "0 0 0 1 * ?") // runs on the first day of each month
    public void doStuffOnFirstDayOfMonth() {
        Date now = DateUtils.addDays(new Date(), -1); // "now" is now on the last day of the month
    }
    

    I use this to generate statistics for a month of data. The routine should run on the first day of the next month to be sure to capture all data of the full previous month.

    While this does not answer the question in the sense of having a Cron Expression for the last day of the month, it still can be a solution for jobs which need to run for a full month and this as soon as possible after the month has come to an end.

    0 讨论(0)
  • 2021-01-16 21:13

    Please check this link Cron Maker

    Give your expression in the text box

    0 10 10 L * ?

    0 讨论(0)
  • 2021-01-16 21:13

    Expression syntactically correct with your condition: 0 10 10 L 1/1 ? *

    And this is workaround that you could be interested: Workaround for CronSequenceGenerator Last day of month?

    0 讨论(0)
提交回复
热议问题