简体   繁体   中英

How can I configure Spring Scheduled Task to run in a time range with specific delay?

I need set up spring scheduled time to be executed every 15 minutes from 5 pm till 8 am, how to specify such expression? And also I'd like task be executed on weekdays not just MON-FRI, but according to my implementation of isBusinessDay logic.

Maven Dependency

Part of Spring Context

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

Configuration to enable Scheduling

Reference from Documentation

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

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

Method to fire on the Cron you specified

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

Documentation

Spring Documentation on Scheduling

Spring Boot

Spring Boot example of setup to run for the above cron

On the safe site you need to add the time-zone of the respective country

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

Below is some basic configuration corn expression

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM