• 说说 Spring 定时任务如何大规模企业级运用


    Spring 定时任务简介

    Cloud Native

    定时任务是业务应用开发中非常普遍存在的场景(如:每分钟扫描超时支付的订单,每小时清理一次数据库历史数据,每天统计前一天的数据并生成报表等等), 解决方案很多 ,Spring 框架提供了一种通过注解来配置定时任务的解决方案,接入非常的简单,仅需如下两步:

    1. 在启动类上添加注解@EnableScheduling

    @SpringBootApplication
    @EnableScheduling  // 添加定时任务启动注解
    public class SpringSchedulerApplication {
      
        public static void main(String[] args) {
      
            SpringApplication.run(SpringSchedulerApplication.class, args);
        }
    }
    

    2. 开发定时任务 Bean 并配置相应的定时注解@Scheduled

    @Component
    public class SpringScheduledProcessor {
      
    
    
      /**
         * 通过Cron表达式指定频率或指定时间
         */
        @Scheduled(cron = "0/5 * * * * ?")
        public void doSomethingByCron() {
      
            System.out.println("do something");
        }
        
      /**
         * 固定执行间隔时间
         */
        @Scheduled(fixedDelay = 2000)
        public void doSomethingByFixedDelay() {
      
            System.out.println("do something");
        }
    
    
        /**
         * 固定执行触发频率
         */
        @Scheduled(fixedRate = 2000)
        public void doSomethingByFixedRate() {
      
            System.out.println("do something");
        } 
    }
    

    Spring 定时任务原理

    Cloud Native

    运行原理

    Spring 定时任务核心逻辑主要在 spring-context 中的 scheduling 包中,其主要结构包括:

    • 定时任务解析:通过 ScheduledTasksBeanDefinitionParser 对 XML 定义任务配置解析;也可通过 ScheduledAnnotationBeanPostProcessor对@Scheduled 注解进行任务解析(常见模式)。

    • 定时任务注册登记:上述解析获得的 Task 任务配置会被注册登记至 ScheduledTaskRegistrar 中以备运行使用。

    • 任务定时运行:完成所有任务注册登记后,会通过 TaskScheduler 正式地定时运行相关任务,底层通过 JDK 的 Scheduled

  • 相关阅读:
    Laravel Swagger 使用完整教程
    Go-Admin后台管理系统源码(GO+VUE)编译与部署
    Java开发规范
    判断某点是否在三角形内(Python)
    【SV中的多线程fork...join/join_any/join_none】
    TS流分析
    Atlas2.2.0编译、安装及使用(集成ElasticSearch,导入Hive数据)
    深化服务成工业品电商角逐新焦点
    【25】c++设计模式——>责任链模式
    allure结合python生成测试报告教程
  • 原文地址:https://blog.csdn.net/Candyz7/article/details/126883983