异步任务、邮件任务、定时任务


这篇文章是基于 狂神说视频的总结,参考了Java成长之路仅供个人学习和复习用。

异步任务

AsyncService

package comzsky.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    @Async //开启异步任务
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理。。。。。。");
    }
}

AsyncController

package comzsky.controller;

import comzsky.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        asyncService.hello();
        return "ok";
    }
}

修改启动器

@EnableAsync //开启异步任务
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}

可以观察到当发送 http://localhost:8080/hello 请求时首先返回”ok”待线程执行完毕再输出打印到控制台”数据正在处理。。。。。。”。

邮件任务

SpringBoot中发送邮件步骤

  • 1.添加start模块依赖
  • 2.添加SpringBoot配置
  • 3.调用JavaMailSender接口发送邮件

导入启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

编写application

applicaton.yaml

spring:
  mail:
    host: "smtp.qq.com" #发送邮件服务器
    username: "55******3@qq.com" #负责发送邮件的邮箱地址
    password: "xhb*********ejj" #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
    from: "55******3@qq.com" #发送邮件的地址与上面的username一致
    #开启加密验证
    properties.mail.smtp.ssl.enable: "true"

邮件接口与实现类

封装邮件接口,方便调用。

IMailService

package comzsky.service;

public interface IMailService {
    /**
     * 发送简单邮件
     * @param to // 邮件接收人
     * @param subject //主题
     * @param content //内容
     */
    void sendSimpleMail(String to,String subject,String content);

    /**
     * 发送带附件文件
     * @param to //邮件接收人
     * @param subject //主题
     * @param content //内容
     * @param filePath //附件
     */
    void sendAttachmentMail(String to,String subject,String content,String filePath);
}

IMailServiceImpl 接口实现类

package comzsky.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class IMailServiceImpl implements IMailService {
    //SpringBoot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
    @Autowired
    JavaMailSender mailSender;

    //配置文件中我的qq邮箱
    @Value("${spring.mail.from}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //邮件发送人
        mailMessage.setFrom(from);
        //邮件接收人
        mailMessage.setTo(to);
        //邮件主题
        mailMessage.setSubject(subject);
        //邮件内容
        mailMessage.setText(content);
        //发送邮件
        mailSender.send(mailMessage);
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException {
        //创建MimeMessage对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装: multipart表示支持复杂类型
        MimeMessageHelper mailHelp = new MimeMessageHelper(mimeMessage,true);
        //邮件发送人
        mailHelp.setFrom(from);
        //邮件接收人
        mailHelp.setTo(to);
        //邮件主题
        mailHelp.setSubject(subject);
        //邮件内容 true 表示支持html格式
        mailHelp.setText(content,true);
        //附件
        //FileSystemResource 是Spring的默认文件加载器 注意参数必须是绝对路径
        FileSystemResource file = new FileSystemResource(new File(filePath));
        //File.getName返回由此抽象路径名表示的文件或目录的名称。
        String fileName = new File(filePath).getName();
        mailHelp.addAttachment(fileName,file); //fileName 上传附件名 file 上传文件路径
        mailSender.send(mimeMessage);

    }
}

编写测试类

package comzsky;

import comzsky.service.IMailServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.MessagingException;
@SpringBootTest
class Springboot09TestApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Autowired
    IMailServiceImpl mailService;

    @Test
    void contextLoads() {
        //一个简单的邮件
       mailService.sendSimpleMail("55*******13@qq.com","简单的邮件","我是一个很正经的简单邮件");
    }

    @Test
    void contextLoads2() throws MessagingException {

       //一个复杂的邮件
        mailService.sendAttachmentMail("55*****13@qq.com","这是一个带附件的邮件","我带了附件过来哦","D:\\Downloads\\进度表(1).docx");
    }

}

定时任务

编写Service

ScheduledService

package comzsky.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    //秒 分 时 日 月 周几
    @Scheduled(cron = "0 * * * * 0-7")
    public void hello(){
        System.out.println("hello,你被执行了");
    }
}

修改启动器

@EnableScheduling //开启定时任务
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}

cron常用例子

常用表达式例子

  (1)0/2 * * * * ? 表示每2秒 执行任务

  (1)0 0/2 * * * ? 表示每2分钟 执行任务

  (1)0 0 2 1 * ? 表示在每月的1日的凌晨2点调整任务

  (2)0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业

  (3)0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作

  (4)0 0 10,14,16 * * ? 每天上午10点,下午2点,4点

  (5)0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时

  (6)0 0 12 ? * WED 表示每个星期三中午12点

  (7)0 0 12 * * ? 每天中午12点触发

  (8)0 15 10 ? * * 每天上午10:15触发

  (9)0 15 10 * * ? 每天上午10:15触发

  (10)0 15 10 * * ? 每天上午10:15触发

  (11)0 15 10 * * ? 2005 2005年的每天上午10:15触发

  (12)0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发

  (13)0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发

  (14)0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发

  (15)0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发

  (16)0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发

  (17)0 15 10 ? * MON-FRI 周一至周五的上午10:15触发

  (18)0 15 10 15 * ? 每月15日上午10:15触发

  (19)0 15 10 L * ? 每月最后一日的上午10:15触发

  (20)0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发

  (21)0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发

  (22)0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发


文章作者: Sky
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Sky !
评论
  目录