zoukankan      html  css  js  c++  java
  • SpringBoot中定时任务与异步定时任务的实现

    场景

    若依前后端分离版手把手教你本地搭建环境并运行项目:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

    在上面实现项目搭建的基础上,怎样在SpringBoot中实现定时任务与异步定时任务实现。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    定时任务实现

    新建一个类,类上添加

    @Component
    @EnableScheduling

    注解开启定时任务支持。

    然后类中新建方法,使用

    @Scheduled(fixedRateString = "1000")

    来标识定时任务执行的方法。

    这里使用fixedRateString是因为这样可以通过

    @Scheduled(fixedRateString = "${scheduled.WebRedisPT}")

    这种类似的方式可以从配置文件中读取配置的定时任务执行的频率。

    然后不使用cron表达式方式执行定时任务方法,是因为这样可以设置定时任务的方法

    在一秒内执行多次,这里是1000代表一秒执行1次,如果是500则代表一秒执行2次。

    示例代码

    package com.ruoyi.web.asyncTask;
    
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    
    @Component
    @EnableScheduling
    public class TaskDemo {
    
        private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS");
    
        @Scheduled(fixedRateString = "1000")
        public void taskOne() {
            System.out.println("任务1执行开始时间"+ dateFormat.format(System.currentTimeMillis()));
            System.out.println("公众号:霸道的程序猿");
            System.out.println("任务1执行结束时间"+ dateFormat.format(System.currentTimeMillis()));
        }
    
    }

    执行效果

     

    异步定时任务执行

    当一个系统中需要执行的定时任务比较多且每个任务执行的频率比较快时,如果还是用上面那种方式去实现所有定时任务的话,就会出现线程拥堵、定时任务在指定的时间内执行不完的情况,这时候就得需要异步任务的执行。

    首先新建一个配置类来开启异步定时任务的支持

    package com.ruoyi.web.config;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    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;
    import java.util.concurrent.ThreadPoolExecutor;
    
    @Configuration
    @EnableAsync
    public class ExecutorConfig {
    
        private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
    
        @Bean
        public Executor asyncServiceExecutor() {
            logger.info("start asyncServiceExecutor");
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            //配置核心线程数
            executor.setCorePoolSize(32);
            //配置最大线程数
            executor.setMaxPoolSize(60);
            //配置队列大小
            executor.setQueueCapacity(99999);
            //配置线程池中的线程的名称前缀
            executor.setThreadNamePrefix("async-service-");
    
            // rejection-policy:当pool已经达到max size的时候,如何处理新任务
            // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            //执行初始化
            executor.initialize();
            return executor;
        }
    }

    这里的核心线程数和最大线程数根据自己业务需要和服务器配置自行修改。

    然后再新建一个定时任务执行类,除了添加

    @Component
    @EnableScheduling

    在类上以及添加

    @Scheduled(fixedRateString = "500")

    还要在方法上添加

    @Async("asyncServiceExecutor")

    开始异步定时任务的支持

    完整示例代码

    package com.ruoyi.web.asyncTask;
    
    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 asyncTaskDemo {
    
        @Scheduled(fixedRateString = "500")
        @Async("asyncServiceExecutor")
        public void taskOne() {
            System.out.println("异步定时任务执行");
        }
    }
    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    uniapp请求拦截
    stellar视差插件
    fullpage全屏插件应用
    fullpage全屏插件简介
    WdatePicker日期插件
    Ueditor富文本编辑器
    layer弹出层
    验证码绘制
    Ajax跨域访问
    JQuery封装的ajax方法
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/14790676.html
Copyright © 2011-2022 走看看