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
        }
    
    }
  • 相关阅读:
    Session攻击(会话劫持+固定)与防御
    console调试命令
    javascript获取当前url
    搞不清FastCgi与PHP-fpm之间是个什么样的关系
    MySQL基本语句优化10个原则
    PHP获取类名及所有函数名
    js闭包
    字段、方法、属性
    python面向对象之类成员修饰符
    实现Python代码发送邮件
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/12610398.html
Copyright © 2011-2022 走看看