preface

Technology most of the primer is simpler, copy other people’s code and delete bowdlerize change, also can achieve a basic functions, see a API will probably know how to implement several functions, however, if enough for a technology, and to know the advantages and disadvantages of a technology, and the existing problems and these will need to think a lot of time and of the wind tests the strength, Only enough understanding can be fearless in the face of danger, can be as strong as the wind bug to smile, absolutely fall!

A scheduled task scheduling annotation@Scheduled

This annotation is the main character in spring’s scheduled task and contains several types

@Scheduled(fixedDelay = 2000) 
@Scheduled(fixedRate = 2000) 
@Scheduled(initialDelay = 1000, fixedDelay = 2000)   
@Scheduled(cron = "*/5 * * * * *")
Copy the code

Children who have used timed tasks should have used the above centralized annotations, now a brief introduction

@scheduled (fixedDelay = 2000) Scheduled(fixedRate = 2000) @scheduled (fixedRate = 2000) Scheduled(fixedRate = 2000) The next task is executed @scheduled (initialDelay = 1000, The fixedDelay = 2000) method will not execute immediately. Wait for initialDelay before executing @scheduled (cron = "*/5 * * * * *") at a selected timeCopy the code

@scheduled (fixedRate = 2000) his instructions are that the next mission is executed 2s after the last one, but is that really the case? So let’s verify that

  1. Create a scheduled task class and a scheduled task method

    @component @enablesCheduling public class ScheduleJob {@autoWired private TaskService TaskService;  */ @scheduled (fixedRate = 2000) public void fixedRateTaskR() {*/ Scheduled(fixedRate = 2000) public void fixedRateTaskR taskService.sayHello("fixedRate"); }Copy the code
  2. Create the interface

    public interface TaskService {
        void sayHello(String type);
    }
    Copy the code
  3. Concrete implementation class

    @Override public void sayHello(String type) { try { long startTime = System.currentTimeMillis() / 1000; System.out.println(type + "=>" + startTime + "- task started "); System.out.println(type + "=>" + "); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); }}Copy the code

I’m doing a delay operation on the task thread that I’m executing, and every time I execute it I sleep for 5 seconds, so if I execute it every 2 seconds then the interval of the method is printed out as 2 seconds, so let’s do that and see what happens

FixedRate => 1632646194 - Task Start fixedRate => Task Executing fixedRate => 1632646197 - Task Starting fixedRate => Task Executing fixedRate => 1632646199 - Mission initiatedCopy the code

The result is clearly a 5s interval instead of a 2s interval, indicating that the next task will be executed after the last task has finished. Wow! Wow! Since there is such a problem, if I have to wait for the last task to finish, that is, 2s to execute once can dry! Of course! Do it now!

2 use@AsyncImplementing asynchronous scheduling

  1. Set up the Spring thread pool
/** * @author @description Spring thread pool Configuration class * @date 2021/8/3 */ @enableAsync @Configuration public class SendMsgThreadPoolConfig { @Bean("schedule") public Executor schduleTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(2); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("schedule-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; }}Copy the code
  1. Specifies a thread pool for asynchronous scheduling methods
@Override @Async("schedule") public void sayHello(String type) { try { long startTime = System.currentTimeMillis() / 1000; System.out.println(type + "=>" + startTime + "- task started "); System.out.println(type + "=>" + "); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); }}Copy the code

Let’s do the following again to see the output

FixedRate => Task is executing fixedRate => Task is executing 1632646666 - Task Starts fixedRate => Task is executing fixedRate => Task is executing FixedRate => 1632646671 - Task Starts fixedRate => Task executing fixedRate => 1632646673 - Task startsCopy the code

Look at the console, the time interval is 2 s, 2 s, 3 s, the junior partner might feel strange, why the interval of the 3 s, this is what happened, it is because we create a thread pool, the core of our thread pool threads and the maximum number of threads are two, once every two seconds, the first 4 s two threads are already occupied, the third task execution time, Wait, because the sleep time of the first task thread is 5s, then the third task thread will execute after waiting 1s, that is the reason for the 3s interval. Verify, change the number of threads to 3. Take a look at the console output

FixedRate => 1632647147 - Task Start fixedRate => Task Executing fixedRate => 1632647149 - Task Starting fixedRate => Task Executing fixedRate => Task executing fixedRate => 1632647151 - Task Start fixedRate => Task executionCopy the code

This is the execution interval of 2s.