springboot与任务

异步任务

  • @Async标记在方法上,指定改方法为一个异步任务
  • @EnableAsync启动异步任务

定时任务

  • @EnableScheduling 开启定时任务

  • @Scheduled 必填属性cron

    1
    2
    second as well as minute, hour, day of month, month and day of week.
    eg:{@code、 "0 * * * * MON-FRI"}
    1
    2
    3
    4
    5
    @Scheduled(cron = "0 * * * * MON-FRI")
    //周一至周五整秒的时候执行
    public void ScheduledTest(){
    System.out.println("ScheduledTest");
    }
  • cron表达式

邮件任务

引入

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
1
2
3
4
5
spring:
mail:
username: xxxxxxx
password: xxxxxx
host: smtp.163.com
  • 简单邮件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Autowired
JavaMailSenderImpl javaMailSender;

@Test
public void contextLoads() {

SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("sunhao1256@163.com");
simpleMailMessage.setSubject("今晚测试springboot邮件任务");
simpleMailMessage.setText("这是今天晚上的测试内容");
simpleMailMessage.setTo("lssh731105702@qq.com");
javaMailSender.send(simpleMailMessage);

}

注意例如QQ邮箱需要开启ssl

  • 复杂邮件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @Test
    public void sendEmail() throws Exception{
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    //开启编码
    MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
    helper.setFrom("sunhao1256@163.com");
    helper.setSubject("今晚测试springboot邮件任务");
    helper.setText("<h1>这是今天晚上的测试内容</h1>",true);
    helper.setTo("lssh731105702@qq.com");

    //上传文件
    helper.addAttachment("hello.jpg",new File("C:\\Users\\55244\\Desktop\\test.jpg"));

    javaMailSender.send(mimeMessage);
    }