Spring: Cancel @Scheduled annotated task
I am running a Spring Boot application and trying to start two jobs with a certain delay using annotation @Scheduled
.
I would like to cancel these jobs programmatically in a specific state. What's the recommended way to do this? Below is my application config:
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");
}
}
source to share
You need to schedule tasks to run using one of the interface implementations Spring TaskScheduler
, such as TimerManagerTaskScheduler or ThreadPoolTaskScheduler , by 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
the object provides a method to cancel the task (ScheduledFuture.cancel ())
source to share
The scheduling method has a planned future. get a handle to that future in your method and then you can invoke cancellation on it to cancel the job you can reference Spring-Boot stop Scheduled task started using @Scheduled annotation and stop Spring Scheduled execution if it hangs after some fixed time
source to share