SpringSchedule task of timing considerations

In our current project, will involve more or less regular tasks, Spring introduced SpringSchedule after 3.0, which gives us when using Spring, you can easily integrate SpringSchedule. But go easy to use, with when there are some points to note.

Timing task SpringSchedule provided, the default is single-threaded execution , meaning that if more tasks or execute a task takes relatively long time, then obviously easy to see, can easily lead to the rest of the task queuing and congestion.

Since there is such a problem, how to avoid this problem? At this time I can easily think of using a thread pool, multiple threads to run scheduled tasks. Yes, the right solution is to configure the thread pool .

The reason why the default is single-threaded execution, because when we taskSchedule not configured, the default is to create a single-threaded thread pool. DETAILED code analysis Reference: https://blog.csdn.net/weixin_40318210/article/details/78149692

Log task execution thread did not look at the case of the thread pool configuration:

Timing task traffic class code as follows:

@Component
public class TaskConfig {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedDelayString = "5000") //单机
    public void getTask1() throws InterruptedException {
        // lock contention logic code .....


        System.out.println ( "Task 1, the current time:" + dateFormat.format (new Date ()) + ", the thread number:". + Thread.currentThread () getName ());
        //throw new RuntimeException("xxxxx");
        Thread.sleep(10000);
    }

    @Scheduled(cron = "0/5 * *  * * ?")
    public void getTask2() {
        System.out.println ( "Task 2, the current time:" + dateFormat.format (new Date ()) + ", the thread number:". + Thread.currentThread () getName ());
    }

}

  

Task execution log is:

 

 

You can see the thread to perform both tasks is always the same thread.

 

Then we added the thread pool configuration now, the configuration code is as follows:

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler (taskExecutor ());
    }

    // Configure thread pool --- common triggers and tasks
    @Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }
}

  

Next we look at the implementation of regular tasks of information:

 

 

Now see after joining the thread pool, the timing of each task execution thread is constantly changing, and these two tasks can be executed in parallel, you can avoid congestion and queuing tasks .

If your code uses SpringSchedule, but also did not use the thread pool, then rush to modify it.

 

 

Guess you like

Origin www.cnblogs.com/cheng21553516/p/11932945.html