zoukankan      html  css  js  c++  java
  • springboot 定时任务(多线程)

    直接上代码:

    1、定义一个配置类

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.Executor;
    
    @Configuration
    @EnableAsync
    public class ScheduleConfig {
    
        @Value("${schedule.corePoolSize}")  // 引入yml配置
        private int corePoolSize;
        @Value("${schedule.maxPoolSize}")
        private int maxPoolSize;
        @Value("${schedule.queueCapacity}")
        private int queueCapacity;
    
        @Bean
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(corePoolSize);
            executor.setMaxPoolSize(maxPoolSize);
            executor.setQueueCapacity(queueCapacity);
            executor.initialize();
            return executor;
        }
    
    }

    application.yml

    schedule:
      corePoolSize: 10
      maxPoolSize: 100
      queueCapacity: 10
    

    2、定义需要按时执行的服务

    corn语句在线生成器:http://cron.qqe2.com/

    说明:可能会遇到定时任务一下次执行多次的情况,这是由于执行速度很快,corn语句匹配仍然生效导致的。需要修改corn语句,使其精确匹配,比如在秒位置写入0就是这个目的。

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    @EnableScheduling
    public class ScheduleService {
    
        // 每10分钟调用一次
        @Scheduled(cron = "0 0/10 * * * ?")  // corn语句
        @Async
        public void s1() {
            // 服务1
        }
    
        // 每天4点调用一次
        @Scheduled(cron = "0 0 4 * * ?")
        @Async
        public void s2() {
            // 服务2
        }
    
    }
  • 相关阅读:
    most-wanted-letter
    non-unique-elements
    python组建之paramiko的简介和简单使用
    Android平台使用termux,随时随地写代码
    发现生活中数学的美,然后记录下来
    别再用Microsoft Office,改为WPS或者Latex
    office2016 vol 中文版本
    Office 2016 英文版(VOL版)下载
    选择好用的生产力工具
    使用windows(win7和win10),最好用chocolatey
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/12610398.html
Copyright © 2011-2022 走看看