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

后端 未结 3 367
无人共我
无人共我 2021-01-14 18:30

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 we

相关标签:
3条回答
  • 2021-01-14 18:48

    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
    
    0 讨论(0)
  • 2021-01-14 18:50

    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

    0 讨论(0)
  • 2021-01-14 18:59

    May be this link can help you. http://www.quartz-scheduler.org/documentation/quartz-2.x/examples/Example1.html

    0 讨论(0)
提交回复
热议问题