2019-12-24-Spring-Boot与任务

一、异步任务

异步:当发现一个方法是异步的时候,会把这个任务挂起,执行之后的代码,当异步任务可以执行的时候在回调方法

springboot实现异步:

  • @EnableAsync

  • @Async

在主程序添加注解
@EnableAsync  //开启异步注解
@SpringBootApplication
public class Springboot04TaskApplication {
	public static void main(String[] args) {
		SpringApplication.run(Springboot04TaskApplication.class, args);
	}
}

在相应的方法加上    @Async注解

二、定时任务

定时任务主要是两个注解:

  • @EnableScheduling //开启基于注解的定时任务

  • @Scheduled

定时的core表达式:

字段 允许值 允许的特殊字符
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 , - * /
星期 0-7或SUN-SAT 0,7是SUN , - * ? / L C #
特殊字符 代表含义
, 枚举
- 区间
* 任意
/ 步长
? 日/星期冲突匹配
L 最后
W 工作日
C 和calendar联系后计算过的值
# 星期,4#2,第2个星期四
/**
 * econd(秒), minute(分), hour(时), day of month(日), month(月), and day of week(周).
 * 【0 0/15 14,18 * * ?】每天14和18点整,每隔15分钟执行一次
 * 【0 15 10 ? * 1-6】 每月的周一至周六10:15分执行一次
 * 【0 0 2 ? * 6L】 每个月的最后一个周六凌晨2点执行一次
 * 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
 * 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点执行一次
 */
@Scheduled(cron = "0 * * * * MON-TUE")
public void hello(){
    System.out.println("hello.......");
}

三、邮件任务

1、简单邮件发送

void contextLoads() {
    SimpleMailMessage message = new SimpleMailMessage();

    //邮件设置
    message.setSubject("通知-今晚开会");//标题
    message.setText("今晚7:00开会");//内容
    message.setFrom("[email protected]");//发送的邮箱
    message.setTo("[email protected]");//接收的邮箱
    mailSender.send(message);
}
配置文件
[email protected]
spring.mail.password=tuhutzkdbcxodefj
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true//开启ssl安全连接

2、附件邮件发送

void contextLoads() {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setSubject("通知-今晚开会");
    helper.setText("<h1>今晚7:00开会</h1>",true);
    helper.setFrom("[email protected]");
    helper.setTo("[email protected]");
    helper.addAttachment("1.jpg", new File("C:\\Users\\17933\\Pictures\\Saved Pictures\\1.jpg"));
    helper.addAttachment("2.jpg", new File("C:\\Users\\17933\\Pictures\\Saved Pictures\\2.jpg"));
    mailSender.send(mimeMessage);
}
发布了26 篇原创文章 · 获赞 27 · 访问量 6853

猜你喜欢

转载自blog.csdn.net/qq_40705355/article/details/103690976
今日推荐