史上最全SpringBoot教程,从零开始带你深入♂学习(十六)——异步任务、定时任务

Springboot(十六)——异步任务、定时任务

异步任务

1、环境搭建

image

2、编写service层,实现延迟3000毫秒

领取资料


package com.study.service;
//加群1025684353一起吹水聊天
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理。。。。");
    }
}

3、编写controller,调用service层

package com.study.controller;

import com.study.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//加群1025684353一起吹水聊天
@RestController
public class AstncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();//延迟三秒
        return "ok";
    }
}

运行测试

跳转到localhost:8080/hello 的时候会延迟(转圈)三秒
image

解决办法,在springboot中开启异步功能

1、在主启动类开启异步功能

@SpringBootApplication
@EnableAsync  //开启异步注解功能
public class Springboot09TestApplication {
//加群1025684353一起吹水聊天
    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }
}

2、在service层方法中添加注解

领取资料

@Service
public class AsyncService {

    //告诉spring这是一个异步的方法,执行这个方法的时候会自动开启线程池
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();//加群1025684353一起吹水聊天
        }
        System.out.println("数据正在处理。。。。");
    }
}

3、运行测试

瞬间响应,进入到页面
image

领取资料

定时任务

1、在主启动类添加开启定时任务功能的注解

@SpringBootApplication
@EnableAsync  //开启异步注解功能
@EnableScheduling //开启定时功能
public class Springboot09TestApplication {

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

}

2、编写service层,测试定时任务功能

领取资料

@Service
public class ScheduledService {
    //@Scheduled : 什么时候执行
    //在一个特定时间执行这个方法:Timer
    //cron表达式        秒 分 时 月 日 星期
    /*
        0 35 2 * * ?    每天凌晨2:35分执行
        0 0/5 10,18 * * ? 每天10点和18点,每隔5分钟执行一次
        0 15 10 ? * 1-6 每个月的周一到周六10点15分执行一次
     */
    //每隔两秒执行一次
    @Scheduled(cron = "0/2 * * * * ?")
    public void hello(){
        System.out.println("hello被执行了");
    }
}

3、运行测试

image

最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。 可以的话请给我一个三连支持一下我哟,我们下期再见

领取资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值