Spring: Cancel a @Scheduled annotated task

This question already has an answer here:

  • Spring-Boot stop Scheduled Task started using @Scheduled annotation

    4 answers

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");
  }

}

You need to schedule your tasks via one of the implementations of Spring TaskScheduler interface, for example a TimerManagerTaskScheduler or ThreadPoolTaskScheduler, getting ScheduledFuture objects.

public interface TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);

}

ScheduledFuture object provides method to cancel the task (ScheduledFuture.cancel())

The schedule method has a scheduled future. get a handle to this future in your method and then you can call cancel on it to cancel the job
you can refer Spring-Boot stop Scheduled Task started using @Scheduled annotation and stop Spring Scheduled execution if it hangs after some fixed time