Spring调度器的cron表达式 - 仅每年运行一次

4

我Spring的服务看起来像这样

@Scheduled( cron="0 0  7 * * SUN")
public void doSomething() {
    // do something
}

我明白你不能使用第七个值来指定年份。那么使用一个表达式,我能否告诉Spring在特定时间运行一次,比如2020年12月25日上午6点?

谢谢。

3个回答

9
是的,你可以。只需要查看这个答案。简而言之,你可以使用以下格式:
0 0 6 6 9 ? 
| | | | | | 
| | | | | |
| | | | | +----- any day of the week.
| | | | +------- 9th month (September).
| | | +--------- 6th day of the month.
| | +----------- 6th hour of the day.
| +------------- Top of the hour (minutes = 0).
+--------------- Top of the minute (seconds = 0).

文档说明只有6个字段。实际上,尝试添加第7个字段会导致以下错误:_"遇到无效的@Scheduled方法... Cron表达式必须由6个字段组成"_ https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html - Madbreaks
我收到了“无效的cron表达式...必须由六个字段组成...” - ka3ak
年份,Spring似乎不支持年份字段。但是Quartz可以:http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html。 - Erik Pragt

6

如果您传递的是月份,它将每年只运行一次。

@Schedule(cron="0 0 0 25 12 ?") --- it will run 25th December every year 

public void CronExpression(){

//your logic

}

这段代码将在今年运行,您可以使用它。 - Anant T

-1

没问题

@Scheduled( cron="59 59 23 6 12 ? 2020")
public void doSomething() {
    // do something
}

这将在2020年12月6日23:59:59触发


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接