每天1:01:am的春天cron表达

问题描述 投票:154回答:6

我试图让我的代码按照固定的时间表执行,基于Spring cron表达式。我希望每天1:01:am执行代码。我尝试了下面的表达式,但这对我来说并没有起作用。这里的语法有什么问题?

@Scheduled(cron = "0 1 1 ? * *")
public void resetCache() {
    // ...
}
java spring cron cronexpression spring-scheduled
6个回答
475
投票

试试:

@Scheduled(cron = "0 1 1 * * ?")

您可以在下面找到spring论坛的示例模式:

* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight

Cron表达式由六个字段表示:

second, minute, hour, day of month, month, day(s) of week

(*)意味着匹配任何

*/X的意思是“每个X”

?(“无特定值”) - 当您需要在允许该字符的两个字段之一中指定某些内容时有用,而不是另一个字段。例如,如果我希望我的触发器在该月的某一天(例如,第10天)触发,但我不关心一周中的哪一天,我会在当天放置“10” - 月份字段和“?”在星期几的字段中。

PS:为了使其工作,请记住在您的应用程序上下文中启用它:https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support


71
投票

对于我的调度程序,我每天早上6点用它来开火,我的cron符号是:

0 0 6 * * *

如果你想要1:01:am然后将其设置为

0 1 1 * * *

调度程序的完整代码

@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
    //complete scheduled work
}

** 很重要

为了确保调度程序的触发时间正确性,您必须设置像这样的区域值(我在伊斯坦布尔):

@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
    //complete scheduled work
}

您可以从here找到完整的时区值。

注意:我的Spring框架版本是:4.0.7.RELEASE


21
投票

您可以使用@Scheduled(cron ="0 1 1 * * ?")注释您的方法。

0 - 是秒

1- 1分钟

一天1小时。


10
投票

gipinani的回答中缺少一些东西

@Scheduled(cron = "0 1 1,13 * * ?", zone = "CST")

这将在1.01和13.01执行。当您需要每天多次运行没有模式的作业时,可以使用它。

当您在远程服务器中进行部署时,zone属性非常有用。这是在春季4推出的。


6
投票

我注意到的一件事是:Spring CronTrigger不是cron。您最终可能会在有效的cron表达式中使用7个参数(您可以在cronmaker.com上验证),然后不接受它。大多数情况下,您只需删除最后一个参数,一切正常。


1
投票

每天1:01:am的春天cron表达

@Scheduled(cron =“0 1 1?* *”)

有关更多信息,请查看此信息:

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

© www.soinside.com 2019 - 2024. All rights reserved.