Spring @scheduled cron表达式,每个月的第一个星期一

时间:2016-12-01 00:41:39

标签: spring spring-mvc spring-boot cron scheduled-tasks

我正在尝试根据Spring cron表达式在固定的时间表上执行代码。我希望代码能够在每个月的第一个星期一上午10:00执行。

           @Scheduled(cron = "")
           public void sendEmail() {
           // ...
           }

当我写:

@Scheduled(cron = "0 0 12 ? * MON#1")
protected synchronized void execute() {...}

应用程序在启动时打印以下错误:

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'execute': For input string: "1#1"
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(ScheduledAnnotationBeanPostProcessor.java:461) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:331) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 19 common frames omitted

5 个答案:

答案 0 :(得分:3)

我在这里回答了类似的问题 How to fire the job on first monday of month using cron expresssion in spring @Scheduled?

该模式是六个空格分隔的字段的列表:代表秒,分钟,小时,天,月,周日。月份和工作日名称可以作为英文名称的前三个字母给出。 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

您可以为此使用该表达式。一个月的前7天只有一个星期一。

"0 0 10 1-7 * MON"

答案 1 :(得分:1)

0 0 10 ? * 2#1
  • 0 - >第0秒\
  • 0 - >第0分钟| - >上午10时
  • 10 - >第10小时/
  • 2#1 - >每个月的第一个星期一

答案 2 :(得分:0)

@Scheduled(cron =“0 0 7 1-7 * MON”)

答案 3 :(得分:0)

AFAIK,Spring计划不支持完整的unix样式的cron格式。

CronSequenceGenerator

根据您的情况,您可以尝试切换到Quartz,而不是先天调度。

您的触发器应配置为以cron表达式运行:0 0 10 ? * 2#1

Trigger trigger = TriggerBuilder
    .newTrigger()
    .withIdentity("triggerIdentity")
    .withSchedule(CronScheduleBuilder.cronSchedule("0 0 10 ? * 2#1"))
    .build();

答案 4 :(得分:-1)

您可以使用此表达式

 @Scheduled(cron = "0 0 10 ? 1/1 MON#1 *")
相关问题