异步任务
@Async
Service
public class AsyncService {
public void hello(){
System.out.println("数据处理中。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理完成。。。");
}
}
定时任务
@Scheduled
- 前提主程序要开启@EnableScheduling
@Service
public class ScheduledSevice {
// 秒,分,时,日,月,周几
@Scheduled(cron = "* * * * * 1-7") //每秒运行
// @Scheduled(cron = "0 0/5 14,18 * * ?") //每天14点和18点每五分钟执行一次
// @Scheduled(cron = "* 15 10 ? * 1-6") //每个星期一到星期六的10点15分,每秒执行一次
// @Scheduled(cron = "0 0 2 ? * 6L") //每个月的最后一个星期六的2点执行一次
// @Scheduled(cron = "0 0 2 LW * ?") //每个月的最后一个工作日的2点执行一次
// @Scheduled(cron = "0 0 2-4 ? * 1#1") //每个月第一个星期一的2-4点执行一次
public String hello(){
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(now);
System.out.println(time);
return time;
}
}
字段 | 允许值 | 允许的特殊字符 |
---|
秒 | 0-59 | ,-*/ |
分 | 0-59 | ,-*/ |
小时 | 0-23 | ,-*/ |
日期 | 1-31 | ,-*/?LWC |
月份 | 1-12 | ,-*/ |
星期 | 0-7或SUN-SAT 0,7是SUN | ,-*/?LC# |
特殊字符 | 允许值 |
---|
, | 枚举 |
- | 区间 |
* | 人意 |
/ | 步长 |
? | 日/星期的冲突匹配 |
L | 最后 |
W | 工作日 |
C | 和calendar联系后计算过的值 |
# | 星期,4#2,第2个星期四 |
发送邮件
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
配置
spring.mail.username=邮箱
spring.mail.password=获取授权码
spring.mail.host=smtp.qq.com
spring.mail.port=587
#spring.mail.properties.mail.smtp.ssl.anable=true
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
发送简单邮件
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
public void test01(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("通知");
message.setText("我成功把邮件发给你了");
message.setTo("63777887@qq.com");
message.setFrom("63777887@qq.com");
javaMailSender.send(message);
}
发送高级邮件
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
public void test02() throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setSubject("通知");
helper.setText("<p style:'color:red'>我成功把邮件发给你了</p>",true);
helper.setTo("63777887@qq.com");
helper.setFrom("63777887@qq.com");
helper.addAttachment("图片1.png", new File("/Users/edz/Desktop/图片1.png"));
javaMailSender.send(message);
}