SpringBoot 从入门到光头 —— 第十四章 SpringBoot 与任务
1. 异步任务
实现异步任务非常简单,只需要 @Async
和 @EnableAsync
两个注解即可实现
示例代码:
com.yourname.task.service.AsyncService
/**
* @author gregPerlinLi
* @since 2022-01-20
*/
public interface AsyncService {
/**
* hello
*/
void hello();
}
com.yourname.task.service.impl.AsyncServiceImpl
/**
* @author gregPerlinLi
* @since 2022-01-20
*/
@Service
public class AsyncServiceImpl implements AsyncService {
/**
* {@code @Async}: Tell Spring that this is an asynchronous method
*/
@Override
@Async
public void hello() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Data processing...");
}
}
com.yourname.task.controller.AsyncController
/**
* @author gregPerlinLi
* @since 2022-01-20
*/
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping(value = "/hello")
public String hello() {
asyncService.hello();
return "success!";
}
}
com.yourname.task.AsyncApplication
/**
* {@code @EnableAsync}: Open asynchronous annotation
*
* @author gregperlinli
*/
@SpringBootApplication
@EnableAsync
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
2. 定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息。Spring 提供了异步执行调度任务的方式,提供 TaskExecutor
、TaskScheduler
接口。
两个注解: @EnableScheduling
、 @Scheduled
Crom 表达式:
字段 | 允许值 | 允许的特殊字符 |
---|---|---|
秒 | 0~59 | ,-*/ |
分 | 0~59 | ,-*/ |
小时 | 0~23 | ,-*/ |
日期 | 1~31 | ,-*?/LWC |
月份 | 1~12 | ,-*/ |
星期 | 0 |
,-*?/LC# |
特殊字符 | 代表含义 |
---|---|
, |
枚举 |
- |
区间 |
* |
任意 |
/ |
步长 |
? |
日/星期冲突匹配 |
L |
最后 |
W |
工作日 |
C |
和 calendar 联系后计算过的值 |
# |
星期(4#2 ,第 2 个星期三) |
Example:
0 0/5 14,18 * * ?
:每天 14点整和 18 点整,每隔五分钟执行一次0 0 2-4 ? * 1#1
:每个月的第一个周一凌晨 2 点到 4 点期间,每个整点都执行一次0 15 10 ? * 1-6
:每个月的周一至周六 10:15 时执行一次0 0 2 LW * ?
:每个月的最后一个工作日凌晨 2 点执行一次0 0 2 ? * 6L
:每个月的最后一个周六凌晨 2 点执行一次
示例代码:
com.yourname.task.service.ScheduleService
/**
* @author gregPerlinLi
* @since 2022-01-20
*/
public interface ScheduleService {
/**
* hello
*/
void hello();
}
com.yourname.task.service.impl.ScheduleServiceImpl
/**
* @author gregPerlinLi
* @since 2022-01-20
*/
@Service
public class ScheduleServiceImpl implements ScheduleService {
/**
* Second, minute, hour, day of month, month, day of week<br/>
* Example: {@code 0 * * * * MON-FRI}<br/>
* {@code 0,1,2,3,4,5 * * * * MON-FRI }<br/>
* {@code 0-10 * * * * MON-FRI }<br/>
* {@code 0/5 * * * * MON-FRI} Every 5 seconds<br/>
*/
@Override
@Scheduled(cron = "0/5 * * * * MON-FRI")
public void hello() {
System.out.println("hello ...");
}
}
com.yourname.task.TaskApplication
/**
* {@code @EnableAsync}: Open asynchronous annotation
* {@code @EnableScheduling}: Enable annotation based scheduled tasks
*
* @author gregperlinli
*/
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
3. 邮件任务
邮件发送需要引入:
spring-boot-starter-mail
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
SpringBoot 自动配置
MailSenderAutoConfiguration
定义
MailPropertie
内容,配置在application.yaml
中自动装配
JavaMailSender
测试邮件发送
示例代码:
application.yaml
spring:
mail:
username: gregperlinli@qq.com
password: abcdefghijklmnop
host: smtp.qq.com
port: 465
properties:
mail:
smtp:
ssl:
enable: true
auth: true
starttls:
enable: true
com.yourname.task.test.TaskApplicationTest
/**
* @author gregperlinli
*/
@SpringBootTest
class TaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
// Mail setting
message.setSubject("通知:今晚开会");
message.setText("开会日期:2022-01-20\n开会时间:20:30\n开会地点:102室");
message.setTo("gregperlinli@outlook.com");
message.setFrom("gregperlinli@qq.com");
mailSender.send(message);
}
@Test
void test2() throws Exception {
// 1. Create a complex message mail
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// Mail setting
helper.setSubject("通知:今晚开会");
helper.setText("开会日期:<b style='color:red'>2022-01-20</b><br/>开会时间:<b style='color:red'>20:30</b><br/>开会地点:<b style='color:red'>102室</b>", true);
// Upload attachments
helper.addAttachment("Info.jpg", new File("/Users/gregperlinli/浩浩/WechatIMG3538.jpeg"));
helper.addAttachment("Notice.jpg", new File("/Users/gregperlinli/浩浩/WechatIMG13669.jpeg"));
helper.setTo("gregperlinli@outlook.com");
helper.setFrom("gregperlinli@qq.com");
mailSender.send(mimeMessage);
}
}