Springboot uses Scheduled timed tasks

Time:2022-8-18

1. Single-threaded useScheduled

  1. Add to the startup class Application@EnableSchedulinAnnotation, open spring scheduled task
  2. Create a task class, add@Componentannotation
  3. add to the method@Scheduled()Annotation, there are the following three ways
// corn mode
     @Scheduled(cron = "0 0 0 0/1 * ?")
     // fixedDelay: Execute again after a few seconds after the last task is executed,
     // initialDelay: Delay a few milliseconds to execute the task after the application starts
    @Scheduled(initialDelay =2000,fixedDelay = 2000)
    // fixedRate is executed a few milliseconds after the start of the last task execution,
    @Scheduled(initialDelay =2000,fixedRate = 5000)

Notice:All tasks here are executed with one thread, because spring's Scheduled default number of threads = 1, so multi-threading is not supported here

Second, the use of multi-threadingScheduled

  1. Modify the thread pool configuration of spirng's native Scheduled to meet the required multi-threading and other functions

    1. Modify the configuration using the configuration file

      spring:
        http:
          task:
            scheduling:
              pool:
                # number of threads
                size: 3
                # mission name
              thread-name-prefix: timing task
              # Whether to wait for the execution of the scheduled task to complete when the application is closed. The default is false, it is recommended to set it to true
              shutdown:
                await-termination: true
                # The maximum time to wait for the task to complete, in seconds. The default is 0, set according to your own application
                await-termination-period: 60
    2. Use configuration class

      @Slf4j
      @Configuration
      public class ScheduledConfig {
      
          // Configure the scheduled task thread pool
          @Bean
          public ThreadPoolTaskScheduler taskScheduler() {
              ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
              executor.setPoolSize(5);
              executor.setThreadNamePrefix("Scheduled task-");
              // executor.setth
              // Whether to wait for the execution of the scheduled task to complete when the application is closed. The default is false, it is recommended to set it to true
              executor.setWaitForTasksToCompleteOnShutdown(true);
              // The maximum time to wait for the task to complete, in seconds. The default is 0, set according to your own application
              executor.setAwaitTerminationSeconds(120);
              return executor;
          }
      }
  1. Using an asynchronous thread pool

    Create a thread pool and@Scheduled()add@Asyncannotation,

    Notice: After using async,fixedDelayThe mode cannot take effect, so if there is this mode, you cannot add@Async

        @Async
        @Scheduled(cron = "0 0 0 0/1 * ?")
        public void excute() {
            //dosomething
        }
    @Slf4j
    @Configuration
    @EnableAsync
    public class AsyncConfig { //implements AsyncConfigurer
    
        @Value(value = "${async.corePoolSize}")
        private int corePoolSize;
    
        @Value(value = "${async.maxPoolSize}")
        private int maxPoolSize;
    
        @Value(value = "${async.queueCapacity}")
        private int queueCapacity;
        //
        //@Autowired
        //private HttpTaskRejectHandler httpTaskRejectHandler;
    
        //If the bean name is not taskExecutor, add the name to @Async("httpTaskExecutor").
        @Bean
        public ThreadPoolTaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(corePoolSize);
            executor.setMaxPoolSize(maxPoolSize);
            executor.setQueueCapacity(queueCapacity);
            executor.setThreadNamePrefix("Asynchronous task -");
            //The queue is full, the thread is rejected to execute the policy, print
            // executor.setRejectedExecutionHandler(httpTaskRejectHandler);
            //The queue is full, discard the oldest task
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
            executor.initialize();
            return executor;
        }
    }