Home >Java >javaTutorial >How to solve the Scheduled single-thread execution problem in SpringBoot

How to solve the Scheduled single-thread execution problem in SpringBoot

WBOY
WBOYforward
2023-05-12 13:04:121768browse

Problem description

When using Scheduled tasks in SpringBoot, it was found that the execution of a certain task occupied a large amount of resources, causing other tasks to fail to execute.
Similar to the following simulation scenario, the test1 scheduled task simulation has an execution time of five seconds. At this time, it will synchronously affect the execution of the test2 task, causing the test2 task to also be executed every five seconds.

    @Scheduled(fixedRate = 1000)
    public void test1() throws InterruptedException {
        log.info(Thread.currentThread().getName() + " | task01 ");
        Thread.sleep(5000);
    }

    @Scheduled(fixedRate = 2000)
    public void test2() {
        log.info(Thread.currentThread().getName() + " | task02 ");
    }

How to solve the Scheduled single-thread execution problem in SpringBoot

Cause analysis:

After reviewing relevant information, it was found that the default number of threads for Scheduled timing tasks is only one, and it will be synchronized when scheduling scheduled tasks. Scheduling, one execution is completed before another is executed, which is the direct cause of the problem.

Solution:

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 设置线程数量
        taskScheduler.setPoolSize(50);
        return taskScheduler;
    }

Add a configuration and set the number of TaskScheduler threads to multiple, so that when executed again, it will be executed asynchronously, and each scheduled task will not affect each other.

How to solve the Scheduled single-thread execution problem in SpringBoot

Supplement:

Using the TimerTask included in the following Java util package can also execute scheduled tasks.
The TimerTask in the following parameters is the task to be executed. 0 means that the first execution is delayed by 0 seconds, and 3000 means that it is executed every 3000 milliseconds.

						// true表示定时任务创建为守护线程
                        Timer timer = new Timer(true);
                        //timer.scheduleAtFixedRate();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                logger.info(Thread.currentThread().getName() + "************"+ftpGaFilePrefix);
                            }
                        }, 0, 3000);

The above is the detailed content of How to solve the Scheduled single-thread execution problem in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete