Spring Boot 整合定时任务和异步任务处理

1.定时任务

Spring Boot 使用注解方式开启定时任务,分为3步

1)启动类里面加上 @EnableScheduling 注解开启定时任务,自动扫描标记了@Scheduled 注解的方法

@SpringBootApplication
@EnableScheduling
public class BaseProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(BaseProjectApplication.class, args);
    }

}

2)定时任务业务类加上 @Component 注解,用于被容器扫描

3)定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次

@Component
public class TestTask {

    @Scheduled(fixedRate=2000)//两秒执行一次
    public void sum() throws InterruptedException{
        System.out.println("结束 当前时间:"+new Date());

    }
}       

常用定时任务表达式配置

(1)fixedRate: 定时多久执行一次(上一次开始执行时间点后xx毫秒再次执行)

(2)fixedRateString: 定时多久执行一次(上一次开始执行时间点后xx毫秒再次执行),字符串形式,可以通过配置文件指定

(3)fixedDelay: 定时多久执行一次(上一次执行结束时间点后xx毫秒再次执行)

(4)fixedDelayString: 定时多久执行一次(上一次执行结束时间点后xx毫秒再次执行),字符串形式,可以通过配置文件指定

(5)cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒。crontab 工具 https://tool.lu/crontab/

@Scheduled(fixedRate=2000)//两秒执行一次
@Scheduled(fixedRateString="2000")//两秒执行一次

@Scheduled(fixedDelay=2000)//两秒执行一次
@Scheduled(fixedDelayString="2000")//两秒执行一次

@Scheduled(cron="*/2 * * * * *")//每两秒执行一次

2.异步任务

Spring Boot 使用注解方式开启异步任务,分为3步

1)启动类里面加上 @EnableAsync 注解开启异步任务,自动扫描标记了 @Async 注解的方法

@SpringBootApplication
@EnableAsync   //开启异步任务
public class XdclassApplication {
    public static void main(String[] args) {
        SpringApplication.run(XdclassApplication.class, args);
    }
}

2)异步任务业务类加上 @Component 注解,用于被容器扫描

3)异步执行的方法加上注解 @Async 表示该方法可以异步执行,也可以在异步任务业务类加上 @Async 表示该类中的所有方法可以异步执行

@Component
@Async
public class AsyncTask {

    public void task1() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时="+(end-begin));
    }

    public void task2() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时="+(end-begin));
    } 

    public void task3() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任务3耗时="+(end-begin));
    }

    //获取异步结果
    public Future<String> task4() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任务4耗时="+(end-begin));
        return new AsyncResult<String>("任务4");
    }

    public Future<String> task5() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任务5耗时="+(end-begin));
        return new AsyncResult<String>("任务5");
    }

    public Future<String> task6() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务6耗时="+(end-begin));
        return new AsyncResult<String>("任务6");
    }

}

测试代码如下:

@RestController
@RequestMapping("/api/v1")
public class UserController {
    @Autowired
    private AsyncTask task;

    @GetMapping("async_task")
    public JsonData exeTask() throws InterruptedException{

        long begin = System.currentTimeMillis();

//        task.task1();
//        task.task2();
//        task.task3();

        Future<String> task4 = task.task4();
        Future<String> task5 = task.task5();
        Future<String> task6 = task.task6();
        for(;;){
            if (task4.isDone() && task5.isDone() && task6.isDone()) {
                break;
            }
        }

        long end = System.currentTimeMillis();

        long total = end-begin;
        System.out.println("执行总耗时="+total);
        return JsonData.buildSuccess(total);
    }
}

注意点:

1)要把异步任务封装到类里面,不能直接写到 Controller

2)增加 Future<String>  返回结果 AsyncResult<String>("task执行完成");

3)如果需要拿到结果,需要判断全部的 task.isDone();

原文地址:https://www.cnblogs.com/jwen1994/p/11372615.html

时间: 2024-08-30 11:16:36

Spring Boot 整合定时任务和异步任务处理的相关文章

SpringBoot整合定时任务和异步任务处理 3节课

1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类             timer:配置比较麻烦,时间延后问题             timertask:不推荐 2.Quartz框架             配置更简单             xml或者注解 3.SpringBoot使用注解方式开启定时任务             1)启动类里面 @Ena

SpringBoot整合定时任务和异步任务处理

SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题,不推荐 timertask:不推荐 2.Quartz框架(复杂定时任务可以使用,spring 或springmv项目) 配置更简单 xml或者注解 具体说明后续...... 3.SpringBoot使用注解方式开启定时任务(springboot项目推荐使用) 1)启动类里面 @EnableSched

spring boot 整合 quartz 集群环境 实现 动态定时任务配置【原】

最近做了一个spring boot 整合 quartz  实现 动态定时任务配置,在集群环境下运行的 任务.能够对定时任务,动态的进行增删改查,界面效果图如下: 1. 在项目中引入jar 2. 将需要的表导入数据库 官网上有不同数据库的脚本,找到对应的,导入即可 3. java 代码 将quartz 的相关配置文件,配置为暴露bean,方便后期引用. 有一处关键的地方,就是注入spring 上下文,也可以算是一个坑.如果,不注入spring 上下文,那么新添加的定时任务job,是新new 的一个

Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的介绍请阅读Apache Kafka简介与安装(一),关于Kafka安装请阅读Apache Kafka安装,关于Kafka集群环境搭建请阅读Apache Kafka集群环境搭建 .这里关于服务器环境搭建不在赘述. Spring Kafka整合Spring Boot创建生产者客户端案例 创建一个kafk

Spring Boot (十三): Spring Boot 整合 RabbitMQ

1. 前言 RabbitMQ 是一个消息队列,说到消息队列,大家可能多多少少有听过,它主要的功能是用来实现应用服务的异步与解耦,同时也能起到削峰填谷.消息分发的作用. 消息队列在比较主要的一个作用是用来做应用服务的解耦,消息从消息的生产者传递到消息队列,消费者从消息队列中获取消息并进行消费,生产者不需要管是谁在消费消息,消费者也无需关注消息是由谁来生产的.在分布式的系统中,消息队列也会被用在其他地方,比如分布式事务的支持,代表如阿里开源的 RocketMQ . 当然,我们本篇文章的主角还是 Ra

spring boot 整合spring Data JPA+Spring Security+Thymeleaf框架(上)

最近上班太忙所以耽搁了给大家分享实战springboot 框架的使用. 下面是spring boot 整合多个框架的使用. 首先是准备工作要做好. 第一  导入框架所需的包,我们用的事maven 进行对包的管理. 以上的举例是本人的H5DS的真实的后台管理项目,这个项目正在盛情融资中,各位多多捧点人场.关注一下软件发展的动态,说不定以后就是您的生活不可或缺的软件哟. 点击打开链接.闲话少说.现在切入正题. 第二,写点配置文件 第三,spring data -设计一个简单的po关系,这里需要下载一

spring boot整合jsp的那些坑(spring boot 学习笔记之三)

Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <depend

Spring boot整合jsp

这几天在集中学习Spring boot+Shiro框架,因为之前view层用jsp比较多,所以想在spring boot中配置jsp,但是spring boot官方不推荐使用jsp,因为jsp相对于一些模板引擎,性能都比较低,官方推荐使用thymeleaf,但是Spring boot整合jsp的过程已经完成,在这里记录一下. 这篇博文是在LZ上篇文章spring boot+mybatis整合基础上写的,开发工具仍然是Intellij idea.这篇文章的重点是Intellij idea的设置,否

企业分布式微服务云SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis

Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方法都比较老,比较繁琐.查了一下文档,实际已经支持较为简单的整合与使用.下面就来详细介绍如何在Spring Boot中整合MyBatis,并通过注解方式实现映射. 整合MyBatis 新建Spring Boot项目,或以Chapter1为基础来操作 pom.xml中引入依赖 这里用到spring-bo