anguspcw
anguspcw

Reputation: 306

Spring schedule not run multi threading

I have two async tasks in schedule class which are testAsyncTask1() and testAsyncTask2(). The thread is stuck in the while(true) of testAsyncTask1() therefore the testAsyncTask2() cannot be executed. How can I run testAsyncTask1() and testAsyncTask2() into multiple threading to avoid the above situation?

Schedule Class

@Configuration
@EnableAsync
@EnableScheduling
public class Schedule extends AbstractSchedule {

    @Async
    @Scheduled(cron = ScheduleTime.EVERY_10SECONDS, zone = TimeZone.PST)
    public void testAsyncTask1() {
        System.out.println("Thread 1");
        logInfo(SCHEDULER_NAME, "Thread 1", " records updated.");
        while (true) {

        }
    }

    @Async
    @Scheduled(cron = ScheduleTime.EVERY_10SECONDS, zone = TimeZone.PST)
    public void testAsyncTask2() {
        System.out.println("Thread 2");
        logInfo(SCHEDULER_NAME, "Thread 2", " records updated.");
    }
}

AbstractBaseSchedule

public abstract class AbstractBaseSchedule extends ScheduleConfig {

}

ScheduleConfig

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    private static final int POOL_SIZE = 10;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(POOL_SIZE);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }
}

Upvotes: 0

Views: 2415

Answers (1)

Mohsen
Mohsen

Reputation: 4633

You need to change set corePoolSize that default value is 1. To do this you should implement AsyncConfigurer in your ScheduleConfig. This will helps you:

@Configuration
@EnableAsync
@EnableScheduling
public class ScheduleConfig implements AsyncConfigurer, SchedulingConfigurer {

    private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(10000);
        executor.setThreadNamePrefix("project-Executor-");
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(scheduledTaskExecutor());
    }

    @Bean
    public Executor scheduledTaskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }
}

Upvotes: 2

Related Questions