Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Cancel a @Scheduled annotated task [duplicate]

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

}
like image 749
31piy Avatar asked Mar 28 '26 20:03

31piy


1 Answers

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())

like image 160
fg78nc Avatar answered Mar 31 '26 12:03

fg78nc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!