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启动类:

  1. package net.xdclass.base_project;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.scheduling.annotation.EnableScheduling;
  6.  
  7. @SpringBootApplication //一个注解顶下面3个
  8. @EnableScheduling //开启定时任务
  9. public class XdclassApplication {
  10.  
  11. public static void main(String[] args) {
  12. SpringApplication.run(XdclassApplication.class, args);
  13. }
  14. }

TestTask.java:

  1. package net.xdclass.base_project.task;
  2.  
  3. import java.util.Date;
  4.  
  5. import org.springframework.scheduling.annotation.Scheduled;
  6. import org.springframework.stereotype.Component;
  7.  
  8. @Component
  9. public class TestTask {
  10.  
  11. @Scheduled(fixedRate=2000) //两秒执行一次
  12. public void sum(){
  13. System.out.println("当前时间:"+new Date());
  14. }
  15.  
  16. }

控制台输出:

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

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

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

    

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

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

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:

  1. package net.xdclass.base_project;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.scheduling.annotation.EnableScheduling;
  7.  
  8. @SpringBootApplication //一个注解顶下面3个
  9. @EnableScheduling //开启定时任务
  10. @EnableAsync //开启异步任务
  11. public class XdclassApplication {
  12.  
  13. public static void main(String[] args) {
  14. SpringApplication.run(XdclassApplication.class, args);
  15. }
  16. }

  AsyncTask.java:

  1. package net.xdclass.base_project.task;
  2.  
  3. import java.util.concurrent.Future;
  4.  
  5. import org.springframework.scheduling.annotation.Async;
  6. import org.springframework.scheduling.annotation.AsyncResult;
  7. import org.springframework.stereotype.Component;
  8.  
  9. @Component
  10. @Async //异步方法,该方法注掉后为同步
  11. public class AsyncTask {
  12.  
  13. public void task1() throws InterruptedException{
  14. long begin = System.currentTimeMillis();
  15. Thread.sleep(1000L);
  16. long end = System.currentTimeMillis();
  17. System.out.println("任务1耗时="+(end-begin));
  18. }
  19.  
  20. public void task2() throws InterruptedException{
  21. long begin = System.currentTimeMillis();
  22. Thread.sleep(2000L);
  23. long end = System.currentTimeMillis();
  24. System.out.println("任务2耗时="+(end-begin));
  25. }
  26.  
  27. public void task3() throws InterruptedException{
  28. long begin = System.currentTimeMillis();
  29. Thread.sleep(3000L);
  30. long end = System.currentTimeMillis();
  31. System.out.println("任务3耗时="+(end-begin));
  32. }
  33.  
  34. //获取异步结果
  35.  
  36. public Future<String> task4() throws InterruptedException{
  37. long begin = System.currentTimeMillis();
  38. Thread.sleep(2000L);
  39. long end = System.currentTimeMillis();
  40. System.out.println("任务4耗时="+(end-begin));
  41. return new AsyncResult<String>("任务4");
  42. }
  43.  
  44. public Future<String> task5() throws InterruptedException{
  45. long begin = System.currentTimeMillis();
  46. Thread.sleep(3000L);
  47. long end = System.currentTimeMillis();
  48. System.out.println("任务5耗时="+(end-begin));
  49. return new AsyncResult<String>("任务5");
  50. }
  51.  
  52. public Future<String> task6() throws InterruptedException{
  53. long begin = System.currentTimeMillis();
  54. Thread.sleep(1000L);
  55. long end = System.currentTimeMillis();
  56. System.out.println("任务6耗时="+(end-begin));
  57. return new AsyncResult<String>("任务6");
  58. }
  59.  
  60. }

  UserController.java测试:

  1. package net.xdclass.base_project.controller;
  2.  
  3. import net.xdclass.base_project.domain.JsonData;
  4. import net.xdclass.base_project.task.AsyncTask;
  5.  
  6. import java.util.concurrent.Future;
  7.  
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12.  
  13. @RestController
  14. @RequestMapping("/api/v1")
  15. public class UserController {
  16.  
  17. @Autowired
  18. private AsyncTask task;
  19.  
  20. @GetMapping("async_task")
  21. public JsonData exeTask() throws InterruptedException{
  22.  
  23. long begin = System.currentTimeMillis();
  24.  
  25. // task.task1();
  26. // task.task2();
  27. // task.task3();
  28.  
  29. Future<String> task4 = task.task4();
  30. Future<String> task5 = task.task5();
  31. Future<String> task6 = task.task6();
  32.  
  33. //需要返回结果可以使用该方法
  34. for(;;){
  35. if(task4.isDone() && task5.isDone() && task6.isDone()){
  36. break;
  37. }
  38. }
  39.  
  40. long end = System.currentTimeMillis();
  41. long total = end - begin;
  42. System.out.println("执行总耗时=" + total);
  43. return JsonData.buildSuccess(total);
  44. }
  45.  
  46. }

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

  同步:

  

  异步:

  

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

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. Laravel表单传值

    仔细阅读过Laravel官方文档的就不用看啦~ 整理下之前遇到的关于Laravel表单的一些小问题 表单传值无法传过去,因为laravel做了表单的防护 只需要将{{ csrf_field() }}放 ...

  2. 【Linux】Screen命令

    1.运行screen [root@master2 ~]# screen 2.执行脚本 [root@master2 ~]# sh mgr.sh 命令帮助 更详细的请使用 man screen查看 htt ...

  3. hdu 3911 Black And White (线段树 区间合并)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3911 题意: 给你一段01序列,有两个操作: 1.区间异或,2.询问区间最长的连续的1得长度 思路: ...

  4. day7 笔记

    二进制-----> ASCLL :只能存英文和拉丁字符.-----> gb2312 :只有6700来个中文字符,1980年-----> gbk1.0 :存了2w多字符 ,1995年- ...

  5. 【Gym 100015B】Ball Painting(DP染色)

    题 There are 2N white balls on a table in two rows, making a nice 2-by-N rectangle. Jon has a big pai ...

  6. 用powershell 批量卸载 windows 更新

    $KBID = "KB958488" $KBID1 = "KB976902" cls function Remove-Update { $HotFixes = ...

  7. Linux监控--CPU、内存、I/O

    CPU top命令能够实时监控系统的运行状态,并且可以按照CPU.内存和执行时间进行排序,同时top命令还可以通过交互式命令进行设定显示,通过top命令可以查看即时活跃的进行. 内存 free命令可以 ...

  8. 修复VirtualBox "This kernel requires the following features not present on the CPU: pae Unable to boot – please use a kernel appropriate for your CPU"

    异常处理汇总-开发工具  http://www.cnblogs.com/dunitian/p/4522988.html 修复VirtualBox "This kernel requires ...

  9. java date总结

    Java 8 中 Date与LocalDateTime.LocalDate.LocalTime互转   Java 8中 java.util.Date 类新增了两个方法,分别是from(Instant ...

  10. JS循环语句!

    <1> for(1.初始值(初始值只有一次):2.判断条件:4.状态改变){ 3.执行语句: //如果判断条件为true,则进入死循环:不设执行语句浏览器会未响应: } <2> ...