一年中每个季度的第一个星期五的下一个星期日的 Cron 作业

Cron jobs for next Sunday of first Friday of every quarter of the year

我正在使用 java spring 启动。我需要获取更新为“数据集每季度(三月、六月、九月、十二月)更新的数据,通常在每月的第一个星期五

然后我想 运行 下周日的 Cron 作业(想保留一整个周六作为缓冲)。对于这种情况,Crone 表达式是什么?

cron 作业参考。 https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

spring 启动 cron 作业参考。 https://www.tutorialspoint.com/spring_boot/spring_boot_scheduling.htm

我们需要解决的特殊情况:当星期日是该月的第 1 天或第 2 天时。通过将星期日限制在 3-9 范围内的日子,我们是安全的。当星期天是第 3 天或更晚时,我们可以确定当月有一个星期五。

表达式

0 0 16 3-9 3/3 SUN

表达式将在

触发
Sun, Mar 7, 2021 at 04:00:00 pm
Sun, Jun 6, 2021 at 04:00:00 pm
Sun, Sep 5, 2021 at 04:00:00 pm
Sun, Dec 5, 2021 at 04:00:00 pm
Sun, Mar 6, 2022 at 04:00:00 pm

表达式可以这样测试:

    var sundays = CronExpression.parse("0 0 16 3-9 3/3 SUN");
    var nextDate = LocalDateTime.now();
    var dateFormatter = DateTimeFormatter.ofPattern("EEE, MMM d, yyyy 'at' hh:mm:ss a");

    for (var i = 0; i < 5; i++) {
        nextDate = sundays.next(nextDate);
        System.out.println(nextDate.format(dateFormatter));
    }

我们可以通过查看 2024 年 6 月来验证特例是否如描述的那样工作

Sun, Jun 9, 2024 at 04:00:00 pm

来自 OP 的评论

We can verify this case in May 2021. where saturday is first day of month. So instead of 2nd May Sunday, we need 9th May Sunday. Which is sunday after first Friday of month.

2021 年 5 月不在所讨论的季度时间表内,但我们可以通过将月份锁定到 5 月来测试这种情况,并保持表达式的其余部分不变,如下所示:

0 0 16 3-9 5 SUN

上面的测试代码将 return Sun, May 9, 2021 at 04:00:00 pm 这是 OP 所要求的。