第⼗⼀章 玩转新版SpringBoot2.X整合定时任务和异步任务

1 SpringBoot2.X 定时任务 schedule 讲解
简介:讲解什么是定时任务和常⻅定时任务区别
  • 什么是定时任务,使⽤场景
    • 某个时间定时处理某个任务
    • 发邮件、短信等
    • 消息提醒​​​​​​

      订单通知

      统计报表系统

  • 常⻅定时任务 
    • Java⾃带的java.util.Timer类配置⽐较麻烦,时间延后问题
    • Quartz框架: 配置更简单,xml或者注解适合分布式或者⼤型调度作业
    • SpringBoot框架⾃带
  •  SpringBoot使⽤注解⽅式开启定时任务
    1. 启动类⾥⾯ @EnableScheduling开启定时任务,⾃动扫描
    2. 定时任务业务类 加注解 @Component被容器扫描
    3. 定时执⾏的⽅法加上注解 @Scheduled(fifixedRate=2000) 定期执⾏⼀次 (两秒执行一次)

1.

//使用SpringBoot启动注解
@SpringBootApplication
@ServletComponentScan //扫描包
@EnableScheduling //开启定时任务,自动扫描定时任务包
public class DemoProjectApplication {
    public static void main(String[] args){
        SpringApplication.run(DemoProjectApplication.class);
    }
}

2-3

/**
 * 定时统计订单,金额
 */
@Component //扫描包
public class VideoOrderTask {
    //定时任务每两秒执行一次
    @Scheduled(fixedRate = 2000)
    public void sum(){
        //金额的查询 LocalDateTime.now()获取当前时间
        DecimalFormat decimalFormat = new DecimalFormat("##"); //设置格式

        System.out.println(LocalDateTime.now()+"当前交易额" +decimalFormat.format(Math.floor(Math.random()*100)+1));
    }
}

 运行结果:

 2 SpringBoot2.X多种定时任务配置实战

简介:SpringBoot常⽤定时任务表达式配置和在线⽣成器 

  • cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
    • crontab ⼯具 https://tool.lu/crontab/
  • fifixedRate: 定时多久执⾏⼀次(上⼀次开始执⾏时间点后xx秒再次执⾏;)
  • fifixedDelay: 上⼀次执⾏结束时间点后xx秒再次执⾏

 

//多种定时任务
    //fifixedRate: 定时多久执⾏⼀次(上⼀次开始执⾏时间点后xx秒再次执⾏;)
    //fifixedDelay: 上⼀次执⾏结束时间点后xx秒再次执⾏
    //cron: * * * * * * 秒,分,时,天,月,周(0-7)0和7代表周日
    @Scheduled(cron = "0 */1 * * * *") //每一分钟执行一次
    public  void sum2(){
        //金额的查询 LocalDateTime.now()获取当前时间
        DecimalFormat decimalFormat = new DecimalFormat("##"); //设置格式

        System.out.println(LocalDateTime.now()+"当前交易额" +decimalFormat.format(Math.floor(Math.random()*100)+1));
    }

运行结果:

 

3集 玩转SpringBoot2.x异步任务EnableAsync实战 

简介:讲解什么是异步任务,和使⽤SpringBoot2.x开发异步任务实战 

  • 什么是异步任务和使⽤场景:适⽤于处理log、发送邮件、短信……
    • 下单接⼝->查库存 1000
    • 余额校验 1500
    • ⻛控⽤户1000
  • 启动类⾥⾯使⽤@EnableAsync注解开启功能,⾃动扫描
  • 定义异步任务类并使⽤@Component标记组件被容器扫描,异步⽅法加上@Async
//使用SpringBoot启动注解
@SpringBootApplication
@ServletComponentScan //扫描包
@EnableScheduling //开启定时任务,自动扫描定时任务包
@EnableAsync //开始异步类支持,自动扫描包
public class DemoProjectApplication {
    public static void main(String[] args){
        SpringApplication.run(DemoProjectApplication.class);
    }
}

 异步类:

@Component //注入扫包点
@Async //使该类成为异步类
public class AsyncTask {
    public void tesk1(){
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task1");
    }

    public void tesk2(){
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task2");
    }

    public void tesk3(){
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task3");
    }
}

测试类:

  //注入异步类
    @Autowired
    private AsyncTask asyncTask;
    @GetMapping("testAsync")
    public JsonData testAsync(){
        long begin = System.currentTimeMillis();

        asyncTask.tesk1();
        asyncTask.tesk2();
        asyncTask.tesk3();
        long end = System.currentTimeMillis();

        return JsonData.buildSuccess("使用异步类执行tesk的时间:"+(end-begin));
    }

 运行结果:

4集 玩转SpringBoot2.x异步任务Future实战 

简介:使⽤SpringBoot2.x开发异步任务Future获取结果 

定义异步任务类需要获取结果 

  • 注意点: 
    • 要把异步任务封装到类⾥⾯,不能直接写到Controller
    • 增加Future 返回结果 AsyncResult("task执⾏完成");
    • 如果需要拿到结果 需要判断全部的 task.isDone()

 

 启动类附上章 

异步方法:

  public Future<String> tesk4(){ //异步使用Future来接收结果
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>("返回结果task4");
    }

    public Future<String> tesk5(){
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new AsyncResult<String>("返回结果task5");
    }

 异步测试类:

 //使用异步类放回结果
    @GetMapping("testFuture")
    public JsonData testFuture(){  //测试有返回值的异步类
        long begin = System.currentTimeMillis();

        Future<String> tesk4 = asyncTask.tesk4();
        Future<String> tesk5 = asyncTask.tesk5();

        for (;;){
            if (tesk4.isDone() && tesk5.isDone()){ //查看两个异步方法是否全部执行完成
                try {
                    String resultForTest4 = tesk4.get();
                    System.out.println(resultForTest4);

                    String resultForTest5 = tesk5.get();
                    System.out.println(resultForTest5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }finally {
                    break;
                }
            }
        }

        long end = System.currentTimeMillis();

        return JsonData.buildSuccess("使用异步类有返回值的执行tesk的时间:"+(end-begin));
    }

请求接口:

 

返回结果:
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值