How to stop a scheduled task that was started using @Scheduled annotation?
Option 1: Using a post processor
Supply ScheduledAnnotationBeanPostProcessor
and explicitly invoke postProcessBeforeDestruction(Object bean, String beanName)
, for the bean whose scheduling should be stopped.
Option 2: Maintaining a map of target beans to its Future
private final Map<Object, ScheduledFuture<?>> scheduledTasks =
new IdentityHashMap<>();
@Scheduled(fixedRate = 2000)
public void fixedRateJob() {
System.out.println("Something to be done every 2 secs");
}
@Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}
class CustomTaskScheduler extends ThreadPoolTaskScheduler {
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, startTime, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
}
When the scheduling for a bean has to be stopped, you can lookup the map to get the corresponding Future
to it and explicitly cancel it.
How to disable @Scheduled method via properties file?
Empty string is an incorrect cron expression. If you want to disable scheduler in particular condition just use @Profile
annotation or if you have to operate on property use @ConditionalOnProperty
annotation from Spring Boot.
@Component
@ConditionalOnProperty(prefix = "spring.cron", name = "expression")
public class MyScheduler {
@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() throws .. { .. }
}
Related Topics
How to Set a Ttl for @Cacheable
How to Set the Radio Button Based on the Value Fetched from the Database
Rounded Swing Jbutton Using Java
How to Remove All Special Character in a String Except Dot and Comma
Check Username and Password in Java Database and Give Wrong Password Message If False
After Spring Boot 2.0 Migration: Jdbcurl Is Required With Driverclassname
How to Store a Large (10 Digits) Integer
Spring Boot JPA - Onetomany Relationship Causes Infinite Loop
Javafx Column in Tableview Auto Fit Size
Autowiring Httpservletrequest in Spring Controller
How to Call an Excel Vba Macro from Java Code
Determine the Number of Pages in a Pdf File
In Java How to Extract Exact Domain Name from Url
How to Use Limit in Spring Within SQL Query
How to Replace Dot (.) in a String in Java
@Valid Annotation Is Not Working as Expected
How to Get My Loops to Display Horizontally Instead of Vertically
Javac Option to Compile All Java Files Under a Given Directory Recursively