我试图让 cron 作业在遗留的 Java/Spring/Hibernate 项目中工作,所以我决定使用 spring 调度程序。
我希望 myTask.doStuff 在每月第一个星期日的 12:00 运行。
在我的 application-context.xml 中,我配置了我的任务调度程序,如下所示:
<task:scheduled-tasks scheduler="MyTaskScheduler">
<task:scheduled ref="myTask" method="doStuff" cron="0 0 12 ? 1/1 SUN#1 *"/> <!-- Every first Sundy of the month -->
</task:scheduled-tasks>
<task:scheduler id="MyTaskScheduler" pool-size="10"/>
问题 cron 表达式本身是:0 0 12 ? 1/1 太阳#1 *
and myTask
是一个 bean,它有一个名为doStuff
从单元测试运行时效果很好。
当我构建和部署时,我从 spring 中得到了一个 boottime 异常:
Caused by: java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 7 in 0 0 12 ? 1/1 SUN#1 *)
at org.springframework.scheduling.support.CronSequenceGenerator.parse(CronSequenceGenerator.java:233)
at org.springframework.scheduling.support.CronSequenceGenerator.<init>(CronSequenceGenerator.java:81)
at org.springframework.scheduling.support.CronTrigger.<init>(CronTrigger.java:54)
at org.springframework.scheduling.support.CronTrigger.<init>(CronTrigger.java:44)
at org.springframework.scheduling.config.ScheduledTaskRegistrar.afterPropertiesSet(ScheduledTaskRegistrar.java:129)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
鉴于我是第一次使用 cron 表达式,我的第一个假设是我做错了什么,但我使用克朗马克它给了我同样的结果。
所有文档都说: cron 表达式是由六个或七个子表达式(字段)组成的字符串。1
尽管如此,我还是尝试删除第七个元素(年份),因为它不在任何示例中,并收到不同的错误消息:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.scheduling.config.ScheduledTaskRegistrar#0': Invocation of init method failed; nested exception is java.lang.NumberFormatException: For input string: "0#1"
... org.springframework.scheduling 是否支持与其他任何东西不同的 cron 风格?spring 特定的文档只是说“cron 表达式”。
我怎样才能让这个 cron 表达式在这种情况下按预期工作?任何帮助将不胜感激。
目前,我的解决方案是简化这个表达式,使其仅在每个星期日运行,并预先添加一些 Java 逻辑来计算它是该月的哪个星期日,并查看这是否有效 - 但这违背了配置方法的目的,并且似乎是一种反模式。