SpringBoot任务这一块简单介绍上个场景,异步任务,定时任务,邮件任务
异步任务
1.编写service层,这里的异步代码需要放在service层执行
package com.tao.springbootconfig02.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async//开启异步执行,使下面这个方法变成异步执行,这里使用线程休眠让这段代码3秒执行
public void syn(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("异步操作完成!!!");
}
}
编写controller层
这一层没什么特别,直接调用service层api即可
package com.tao.springbootconfig02.controller;
import com.tao.springbootconfig02.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Test {
@Autowired
AsyncService asyncService;
@RequestMapping("/test")
public String test(){
asyncService.syn();
return "test";
}
}
主启动类
@EnableAsync//这里需要加上开启异步注解
@SpringBootApplication
public class SpringbootConfig02Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootConfig02Application.class, args);
}
}
那么原有的执行逻辑是这样的,访问test接口后客户端无任何响应,等待三秒后才有test返回值
但是使用上面的异步写法后,使这个test接口API变成一个异步的,不需要等待service层执行的返回,而是直接请求test接口API客户端直接返回test,无需等待3秒的时间,而service层的syn()异步方法执行3秒完毕后会在服务端打印“异步操作完成!!!”,这个异步可以使用在耗时比较长,但是又不需要返回结果给客户端的操作,那么就可以使用异步任务编写业务;
定时任务
service层
@Service
public class SchediledService {
//second 秒 minute 分 hour 时 day of month 日 month 月 day of week 星期
@Scheduled(cron = "* * * * * *")//这个代表每一秒都执行
//@Scheduled(cron = "0/4 * * * * *")//这个代表0秒开始执行,每隔4秒重复执行
//@Scheduled(cron = "0,1,2,3,4 * * * * *")//这个代表0,1,2,3,4秒都执行一次
/**
* 0 0/5 14,18 * *? 每天14,18整点执行,每隔5分钟一次
* 0 15 10 ? 0 1-6 每月的周1-周6 10.15分执行一次
* 0 0 2 ? * 6L 每个月的最后一个周六凌晨2点执行一次
* 0 0 2 LW * ? 每个月的最后一个工作日凌晨两点执行一次
* 0 0 2-4 ? * 1#1 每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次
*/
public void schediled(){
System.out.println("启动!!!");
}
}
这里定时任务是交给SpringBoot去执行的所以我们不需要编写controller去调用
只需要在主启动类上添加@EnableScheduling注解开启定时任务即可
这个cron对应的表达式,这个表达式个人觉得没必要一定会写,但是要知道什么意思,到真实的业务场景中直接百度即可!!!
结语
Spring提供的原生任务只能适合简单的业务场景,目前市面上比较流行的是分布式调度平台,分布式任务调度平台XXL-JOB