定时执行任务
@EnableScheduling //开启定时执行任务的功能 (在主启动类中添加)
package com.Google;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableAsync//开启异步功能
@EnableScheduling //开启定时执行任务的功能
public class SpringBoot07MailTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot07MailTestApplication.class, args);
}
}
@Scheduled(cron="0/1 * * * * ?") (设置预定的时间),在类上添加注解就可以运行
package com.Google.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class TimeService {
@Autowired
JavaMailSenderImpl senderMail; //需要先配置 邮件配置文件,才能自动注入
@Async //告诉spring这是一个异步方法
public void timeSleep() throws InterruptedException {
Thread.sleep(3000);
System.out.println("邮件正在发送");
}
@Async
@Scheduled(cron="0/1 * * * * ?") //每隔三秒执行一次任务 17879535823
public void sendMail(){ //简单邮箱
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("这是lzl通过java程序发送的测试邮件");
message.setText("这是正文");
message.setTo("2034281742@qq.com");
message.setFrom("2034281742@qq.com");
senderMail.send(message);
System.out.println("邮件已发送");
}
@Async
public void sendMimeMail() throws MessagingException { //发送复杂邮件
MimeMessage mimeMessage = senderMail.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true); //开启multipart,以实现发送附件
messageHelper.setSubject("这是lzl通过java程序发送的测试邮件");
messageHelper.setText("<p style='color:yellow'>这是正文</p>",true);
//附件
messageHelper.addAttachment("图片1",new File("D:\\Instalaltion package\\sunDowm.jpg"));
messageHelper.addAttachment("图片2",new File("D:\\Instalaltion package\\sunDowm.jpg"));
messageHelper.setTo("2034281742@qq.com");
messageHelper.setFrom("2034281742@qq.com");
senderMail.send(mimeMessage);
}
}