如何在SpringBoot中每5分钟从上午9:30到下午4:00运行作业?

qlzsbp2j  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(329)

目前,我在应用程序中配置了以下两个cron表达式,但是作业运行时间超过了下午4:00。
如下面的应用程序日志所示,即使在下午4:00之后,我也会看到日志记录语句。不知道为什么。
应用程序属性


# Starts at 9:30 AM and ends at 10:00 AM. Runs every 5 mins

job.cron1=0 30-55/5 9 * * MON-FRI

# Starts at 10:00 AM and ends at 4:00 PM. Runs every 5 mins

job.cron2=0 */5 10-16 * * MON-FRI

purgedata.java文件

@Scheduled(cron = "${job.cron1}")
public void purgeDBData1() {
    log.info("Purging DB data every 5 mins between 9:30 am - 10:00 am...");
}

@Scheduled(cron = "${job.cron2}")
public void purgeDBData2() {
    log.info("Purging DB data every 5 mins between 10:00 am - 4:00 pm...");
}

应用程序日志:

2021-03-02 16:05:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:10:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
...
....
.....
2021-03-02 16:45:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:50:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:55:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
k7fdbhmy

k7fdbhmy1#

你需要两个老太婆来处理九点半开始的事。共同的部分是从周一到周五每5秒。记住后面的值是包含的,所以范围必须是到 15 ,即 3pm .
小时和分钟跨度不同: 0 30/5 9 ? * MON,TUE,WED,THU,FRI * -在哪里 30/5 9 指每5分钟从上午9:30开始的第9个小时(不含上午10点)。 0 0/5 10-15 ? * MON,TUE,WED,THU,FRI * -在哪里 0/5 10-15 指从上午10点到下午4点的每5分钟一次(不含)
你需要使用 @Schedules 定义嵌套 @Scheduled 注解。

@Schedules ({
    @Schedule(cron = "${job.cron1a}"),       // a cron with 9:30am to 9:59am
    @Schedule(cron = "${job.cron1b}")        // a cron with 10am to 16pm
})
public void purgeDBData1() {
    log.info("Purging DB data every 5 mins between 9:30 am - 10:00 am...");
}
mefy6pfw

mefy6pfw2#

您应该如下配置它

job.cron2=0 */5 10-15 * * MON-FRI

相关问题