1、SpringBoot定时任务schedule讲解

   定时任务应用场景:

  

简介:讲解什么是定时任务和常见定时任务区别

1、常见定时任务 Java自带的java.util.Timer类
             timer:配置比较麻烦,时间延后问题
             timertask:不推荐

2、Quartz框架
             配置更简单
             xml或者注解

3、SpringBoot使用注解方式开启定时任务
             1)启动类里面 @EnableScheduling开启定时任务,自动扫描
             2)定时任务业务类 加注解 @Component被容器扫描
             3)定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次  单位:ms

代码示例:

XdclassApplication.java启动类:

 package net.xdclass.base_project;

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication //一个注解顶下面3个
@EnableScheduling //开启定时任务
public class XdclassApplication { public static void main(String[] args) {
SpringApplication.run(XdclassApplication.class, args);
}
}

TestTask.java:

 package net.xdclass.base_project.task;

 import java.util.Date;

 import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; @Component
public class TestTask { @Scheduled(fixedRate=2000) //两秒执行一次
public void sum(){
System.out.println("当前时间:"+new Date());
} }

控制台输出:

2、SpringBoot常用定时任务配置实战
     简介:SpringBoot常用定时任务表达式配置和在线生成器

1、cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒

    
             1)crontab 工具  https://tool.lu/crontab/

    

    代码示例:(每2s执行一次)

 @Scheduled(cron="*/2 * * * * *")
public void sum(){
System.out.println("当前时间:"+new Date());
}

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

3、SpringBoot2.x异步任务实战(核心知识)
     简介:讲解什么是异步任务,和使用SpringBoot2.x开发异步任务实战
         1、什么是异步任务和使用场景:适用于处理log、发送邮件、短信……等
             下单接口->查库存 100
                     余额校验 150
                     风控用户100
                     ....

2、启动类里面使用@EnableAsync注解开启功能,自动扫描
        
         3、定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async
             注意点:
                 1)要把异步任务封装到类里面,不能直接写到Controller
                 2)增加Future<String> 返回结果 AsyncResult<String>("task执行完成"); 
                 3)如果需要拿到结果 需要判断全部的 task.isDone()
         4、通过注入方式,注入到controller里面,如果测试前后区别则改为同步则把Async注释掉

  代码示例:

  XdclassApplication.java:

 package net.xdclass.base_project;

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication //一个注解顶下面3个
@EnableScheduling //开启定时任务
@EnableAsync //开启异步任务
public class XdclassApplication { public static void main(String[] args) {
SpringApplication.run(XdclassApplication.class, args);
}
}

  AsyncTask.java:

 package net.xdclass.base_project.task;

 import java.util.concurrent.Future;

 import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component; @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");
} }

  UserController.java测试:

 package net.xdclass.base_project.controller;

 import net.xdclass.base_project.domain.JsonData;
import net.xdclass.base_project.task.AsyncTask; import java.util.concurrent.Future; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @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);
} }

  同步/异步执行时间对比:

  同步:

  

  异步:

  

  由此可见,同步与异步,它们的执行效率是不同的,应根据需求进行选择使用。

SpringBoot整合定时任务和异步任务处理 3节课的更多相关文章

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

    SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...

  2. 小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_41、SpringBoot定时任务schedule讲解

    笔记 1.SpringBoot定时任务schedule讲解     简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类            ...

  3. 【SpringBoot】SpringBoot2.x整合定时任务和异步任务处理

    SpringBoot2.x整合定时任务和异步任务处理 一.项目环境 springboot2.x本身已经集成了定时任务模块和异步任务,可以直接使用 二.springboot常用定时任务配置 1.在启动类 ...

  4. SpringBoot2.x整合定时任务和异步任务处理

    SpringBoot2.x整合定时任务和异步任务处理 一.项目环境 springboot2.x本身已经集成了定时任务模块和异步任务,可以直接使用 二.springboot常用定时任务配置 1.在启动类 ...

  5. 【SpringBoot】整合定时任务和异步任务

    ========================10.SpringBoot整合定时任务和异步任务处理 =============================== 1.SpringBoot定时任务s ...

  6. SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)

    一.使用场景 定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等... 二.准备工作 在Spring Boot程序中不需要引入其他Maven依赖 (因为s ...

  7. SpringBoot整合全局异常处理&SpringBoot整合定时任务Task&SpringBoot整合异步任务

    ============整合全局异常=========== 1.整合web访问的全局异常 如果不做全局异常处理直接访问如果报错,页面会报错500错误,对于界面的显示非常不友好,因此需要做处理. 全局异 ...

  8. 数据库操作之整合Mybaties和事务讲解 5节课

    1.SpringBoot2.x持久化数据方式介绍          简介:介绍近几年常用的访问数据库的方式和优缺点 1.原始java访问数据库             开发流程麻烦           ...

  9. SpringBoot整合定时任务异步任务

    1.定时任务 1.开启定时任务 @SpringBootApplication //开启定时任务 @EnableScheduling public class SpringBootDemoApplica ...

随机推荐

  1. Django-website 程序案例系列-4 ORM数据库操作

    数据库表的创建: 使用mysql时注意,在setting.py中的设置: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql' ...

  2. Codeforces Round#500 Div.2 翻车记

    A:签到 #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> # ...

  3. day14 装饰器

    装饰器 本质上就是函数,功能是为其他函数添加附加功能 原则:不修改被修饰函数的源代码,以及调用方式,即完全不能有任何改变 装饰器 = 高阶函数+ 函数嵌套+ 闭包 高阶函数:函数作为参数或者返回一个函 ...

  4. Android canvast View 代码实例

    package com.app.canvastest; import android.content.Context; import android.graphics.Bitmap; import a ...

  5. PKUWC 2019 记

     “连剑都插在了地上,可是我不应该就这么承认失败,想要到达山顶的人,不应该在山脚下就倒下啊” Day -5 (2019.1.15) 学考结束了,文化课暂停一段.早上飞机前往中山纪念中学.纪中好大呀,果 ...

  6. bzoj1597/luogu2900 土地购买 (斜率优化dp)

    首先按x从小到大排序,那么可得: f[i]=min{f[j]+x[i]*maxy[j+1..i]} 然而这样是$O(n^2)$的而且无法做优化. 然后我们考虑:如果对于某一点,存在另一点的x和y都比它 ...

  7. Elasticsearch利用cat api快速查看集群状态、内存、磁盘使用情况

    使用场景 当Elasticsearch集群中有节点挂掉,我们可以去查看集群的日志信息查找错误,不过在查找错误日志之前,我们可以通过elasticsearch的cat api简单判断下各个节点的状态,包 ...

  8. 【POJ3585】Accumulation Degree 二次扫描与换根法

    简单来说,这是一道树形结构上的最大流问题. 朴素的解法是可以以每个节点为源点,单独进行一次dp,时间复杂度是\(O(n^2)\) 但是在朴素求解的过程中,相当于每次都求解了一次整棵树的信息,会做了不少 ...

  9. 斯坦福大学公开课机器学习:Neural network-model representation(神经网络模型及神经单元的理解)

    神经网络是在模仿大脑中的神经元或者神经网络时发明的.因此,要解释如何表示模型假设,我们先来看单个神经元在大脑中是什么样的.如下图,我们的大脑中充满了神经元,神经元是大脑中的细胞,其中有两点值得我们注意 ...

  10. mysql自定义函数与过程中写法的注意事项

    BEGIN #Routine body goes here... /* update szzx_goods_common set gc_id=i where gc_name=(SELECT gc_na ...