Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 908
Daria Bulanova Avatar asked Sep 21 '25 12:09

Daria Bulanova


1 Answers

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

like image 124
dimitrisli Avatar answered Sep 23 '25 00:09

dimitrisli