如何将Spring Scheduled Task配置为在特定延迟的时间范围内运行?

时间:2017-09-18 10:24:12

标签: java spring cron scheduled-tasks

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

3 个答案:

答案 0 :(得分:3)

Maven依赖

Spring Context

的一部分
 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
  </dependency>

启用计划的配置

Reference from Documentation

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

@Configuration
@EnableScheduling
public class MyAppConfig {
//..
}

触发您指定的Cron的方法

Reference from Documentation

// 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() {
    // ..
}

<强>文档

Spring Documentation on Scheduling

春季启动

Spring Boot example of setup to run for the above cron

答案 1 :(得分:0)

答案 2 :(得分:0)

在安全网站上,您需要添加相应国家/地区的时区

// 0/15 -> Every 15 minutes on the clock
// 17-20 -> Between 5pm and 8pm 
@Scheduled(cron="0 0/15 17-20 * * ?",zone="Your time zone")
Ex:--
@Scheduled(cron="0 0/15 17-20 * * ?",zone="Asia/Calcutta")
public void yourJob(){
..........
..........your code
..........
}

以下是玉米表达的一些基本配置

The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.

Example patterns:

"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight