Reputation: 841
I am using ThreadPoolTaskScheduler and Scheduler to create tasks, but when I set a new task I want to remove a certain one or all of them how can I do this?
@Bean
public ThreadPoolTaskScheduler createThreadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setThreadNamePrefix(threadPrefix);
threadPoolTaskScheduler.initialize();
return threadPoolTaskScheduler;
}
Adding the tasks:
private final Scheduler scheduler;
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
public void addTask(){
FixedRateTask update = new FixedRateTask(this::executeOnRateMethod
, initialDelay, waitTime);
taskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
scheduler.setTask(taskRegistrar.scheduleFixedRateTask(update));
}
It seems that calling:
taskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
taskRegistrar.scheduleFixedRateTask(update);
Adds threads to the pool everytime, Also canceling the scheduler is not working:
scheduler.getTask().cancel();
Upvotes: 3
Views: 3052
Reputation: 59
I was a little late with the answer, but maybe it will be useful to someone.
You need to add this line of code to the createThreadPoolTaskScheduler() method:
threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
Upvotes: 0
Reputation: 1109
When you scheduled a future ScheduledFuture<?>
will be returned.The ScheduledFuture<?>
has scheduledFuture.cancel(false)
, it will cancel the scheduled task, which you have placed in the executor.
Upvotes: 1