Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove tasks from ThreadPoolTaskScheduler pool Spring

Tags:

java

spring

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();
like image 521
ivaylo Avatar asked Aug 11 '26 06:08

ivaylo


1 Answers

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.

like image 117
Georgi Peev Avatar answered Aug 12 '26 19:08

Georgi Peev



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!