问题
I need set up spring scheduled time to be executed every 15 minutes from 5 p.m till 8 a.m, 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.
回答1:
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
回答2:
May be this link can help you. http://www.quartz-scheduler.org/documentation/quartz-2.x/examples/Example1.html
回答3:
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
来源:https://stackoverflow.com/questions/46276971/how-can-i-configure-spring-scheduled-task-to-run-in-a-time-range-with-specific-d