【问题标题】:Spring scheduled task cron expression validationSpring定时任务cron表达式验证
【发布时间】:2020-04-23 09:26:17
【问题描述】:

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

@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 星期六

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

感谢您的帮助。

【问题讨论】:

    标签: spring-boot cron


    【解决方案1】:

    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
        }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-12-04
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多