Spring计划任务Cron表达式验证

时间:2020-04-23 09:26:17

标签: spring-boot cron

我正在编写一个计划任务,该任务需要每月每个第一个星期六运行。 我想出了这个:

@Scheduled(cron = "0 0 23 1-7 * SAT")
// Runs on 1st Saturday of each month at 23:00
public void CleanUpScheduledTask() {
}

我是怎么来的呢?

0 0 23意味着每天的晚上11:00

1-7 *表示每月1-7之间

SAT星期六

您如何建议确保上述表达式有效?我如何测试这些功能?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

1。建立Cron表情

使用Spring cron作业表达式

@Scheduled(cron = "[Seconds] [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]")

NB年字段是可选的

  • #用于指定任务应该在星期几开始。

    例如每月的第一个星期六(7#1

  • ?表示没有特定值,可以在“月的一天”或“星期几”字段中使用

  • *代表所有值

因此cron表达式变为

@Scheduled(cron = "0 0 23 ? * 7#1")

2。测试Cron作业

  • 使用Awaitility dependency

      <dependency>
         <groupId>org.awaitility</groupId>
         <artifactId>awaitility</artifactId>
         <scope>test</scope>
      </dependency>
    

-使用Spring Integration testing

@SpringJUnitConfig(CleanScheduler.class)
public class CleanSchedulerUnitTest {
    @Autowired
    private CleanScheduler cleanScheduler;

    @Test
    void cleanUpScheduledTaskShouldReturnSuccess() {
       //Act
        cleanScheduler.cleanUpScheduledTask();
      //Assertions
    }
}

答案 1 :(得分:0)

您可以使用https://www.freeformatter.com/cron-expression-generator-quartz.html之类的在线Cron生成器来生成cron表达式或描述您发布的内容。

0 0 0,23吗? * 7#1 *应该描述并在每月的每月第1个星期六的第二个00:00,分钟:00,00 am和23pm运行。

相关问题