八、SpringBoot之任务(异步,定时,邮件)

异步任务实现

在service中写一个方法

    //告诉Spring这是一个异步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中...");
    }

在controller层调用并跳转页面

    @Autowired
    AsyncService asyncService;

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

现在这个情况下除了在方法上面声明异步@Async外还需要在启动类上面加上@EnableAsync注解来启动异步功能!此时访问localhost:8080/hello就会马上相应页面,后台的方法会延迟三秒后执行,但是页面不会有延迟!这样的页面才会更友好!

总的来说,异步任务就是在业务方法上面加上@Async注解声明这是一个异步方法,再在启动类上用@EnableAsync来启动异步功能!


定时任务

定时任务用到了两个注解@Scheduled和@EnableScheduling
第一个注解是加在方法上面,用参数来声明多久执行一次看代码

@Service
public class ScheduledService {

    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 0 * * * * MON-FRI
     *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     *  【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-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
   // @Scheduled(cron = "0-4 * * * * MON-SAT")
    @Scheduled(cron = "0/4 * * * * MON-SAT")  //每4秒执行一次
    public void hello(){
        System.out.println("hello ... ");
    }
}

对于参数不需要记忆,有这样一个网址,里面可以自动生成

http://www.bejson.com/othertools/cron/


邮件任务

邮件任务的话就需要导入mail的starter了

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

邮件需要声明的首先需要声明一下自己的邮箱什么的吧,这个MailProperties中有参数说明,在配置文件中配置一下相应的

[email protected]
#这里是邮箱的授权码
spring.mail.password=gtstkoszjelabijb
#邮箱的服务器主机
spring.mail.host=smtp.qq.com
#QQ邮箱需要设置安全连接才能使用
spring.mail.properties.mail.smtp.ssl.enable=true

现在开始写测试方法,发邮件

	@Test
	public void contextLoads() {
		//1、创建一个简单的消息邮件
		SimpleMailMessage message = new SimpleMailMessage();
		//邮件设置
		message.setSubject("通知-今晚开会");
		message.setText("今晚7:30开会");

		message.setTo("[email protected]");
		message.setFrom("[email protected]");

		mailSender.send(message);
	}


	@Test
	public void test02() throws  Exception{
		//1、创建一个复杂的消息邮件
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

		//邮件设置
		helper.setSubject("通知-今晚开会");
		helper.setText("<b style='color:red'>今天 7:30 开会</b>",true);
		//从什么到什么from···to···
		helper.setTo("[email protected]");
		helper.setFrom("[email protected]");

		//上传文件
		helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
		helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));

		mailSender.send(mimeMessage);

	}

这就是邮件发送,很简单,我当时还想着定时任务加在邮件上面,一秒发一次,然后我的邮箱被认证为垃圾邮箱了,(哈哈),只是暂时的,后来还是好了!

猜你喜欢

转载自blog.csdn.net/lp20171401131/article/details/106878041
今日推荐