Spring: Cancel a @Scheduled annotated task

Viewed 7758

I am running a Spring Boot app, and trying to get two jobs running with a specific delay using the @Scheduled annotation.

I would like to cancel these jobs programmatically on a particular condition. What's the recommended way of doing this? Following is the configuration of my app:

Main.java

@SpringBootApplication
@EnableScheduling
public class Main implements CommandLineRunner {

  static LocalDateTime startTime = LocalDateTime.now();

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Main.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
  }

}

Job1.java

@Component
public class Job1 {

  @Scheduled(fixedDelay = 10000)
  public void run() {
    System.out.println("Job 1 running");
  }

}

Job2.java

@Component
public class Job1 {

  @Scheduled(fixedDelay = 10000)
  public void run() {
    System.out.println("Job 2 running");
  }

}
2 Answers
Related