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 start/stop @Scheduled task after certain method finishes
A very simple way is to add a boolean switch:
@Scheduled(fixedRate = 1000)
public void scheduledTask() {
if (enabled) {
log.info("scheduled task has been started");
}
}
public void triggerStart() {
enabled = true;
log.info("after this @Scheduled task will start working");
}
public void triggerFinish() {
enabled = false;
log.info("after this @Scheduled task will stop working");
}
Start and stop scheduling task in Spring java
Try to use ScheduledExecutorService. For example, first of all create a ScheduledExecutorService
:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
then create a scheduled task:
ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(
() -> System.out.println("some task"), 0, 30, TimeUnit.SECONDS);
and when you want to cancel the task, do the following:
task.cancel(true);
How to conditionally enable or disable scheduled jobs in Spring?
@Component
public class ImagesPurgeJob implements Job {
private Logger logger = Logger.getLogger(this.getClass());
@Value("${jobs.mediafiles.imagesPurgeJob.enable}")
private boolean imagesPurgeJobEnable;
@Override
@Transactional(readOnly=true)
@Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
public void execute() {
//Do something
//can use DAO or other autowired beans here
if(imagesPurgeJobEnable){
Do your conditional job here...
}
}
}
Related Topics
How to Match "Any Character" in Regular Expression
How to Execute Multiple SQL Statements from Java
Nextdouble() Throws an Inputmismatchexception When I Enter a Double
Do Java Primitives Go on the Stack or the Heap
Throw Checked Exceptions from Mocks with Mockito
When Should We Use a Preparedstatement Instead of a Statement
Java Jtree Directory Structure from File Paths
Last Row Always Removed from Defaulttablemodel, Regardless of Index
This: Cannot Use This in Static Context
Why Is "Final" Not Allowed in Java 8 Interface Methods
How Does Java Store Strings and How Does Substring Work Internally
Jaxb Marshalling Unmarshalling with Cdata
Calling Super Super Class Method
Registering Multiple Keystores in Jvm
How to Create a Hashmap with Two Keys (Key-Pair, Value)
Get a Node's Inner Xml as String in Java Dom
How to Pass a Variable from One Thread Group to Another in Jmeter