如何配置 Spring 计划任务以在具有特定延迟的时间范围内运行?

Dar*_*ova 3 java cron spring scheduled-tasks

我需要设置春季预定时间从下午 5 点到早上 8 点每 15 分钟执行一次,如何指定这样的表达式?而且我希望任务不仅在周一至周五在工作日执行,而且根据我对 isBusinessDay 逻辑的实现。

dim*_*sli 5

Maven 依赖

部分Spring上下文

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
  </dependency>
Run Code Online (Sandbox Code Playgroud)

启用调度的配置

参考文献

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class MyAppConfig {
//..
}
Run Code Online (Sandbox Code Playgroud)

在您指定的 Cron 上触发的方法

参考文献

// 0/15 -> Every 15 minutes on the clock
// 17-20 -> Between 5pm and 8pm on the JVM timezone
// if you want timezone specific there is a 'zone' parameter: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#zone--
@Scheduled(cron="0 0/15 17-20 * * ?")
public void doSomething() {
    // ..
}
Run Code Online (Sandbox Code Playgroud)

文档

Spring 调度文档

弹簧靴

为上述 cron 运行的 Spring Boot 设置示例