定时任务实现的几种方式:
1.Timer是java自带的java.util.Timer类,这个类允许你调度
2.ScheduledExecutorService:
3.Spring Task
添加依赖
创建任务类
4.Quartz
添加依赖
创建配置类
使用Spring Task方法使用邮件来完成定时发送
后台管理系统开发:
1.首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码
2.添加pom.xml依赖
dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.配置application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=1459816730@qq.com
spring.mail.password=gflxxutdklwogbba
spring.mail.default-encoding=UTF-8
##如果不加下面3句,会报530错误
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
4.写Service接口
/**
* 发送简单邮件
*/
void sendMail(String to,String subject,String content);
}
5.实现接口
@Service("mailService")
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Override
public void sendMail(String to, String subject, String content) {
SimpleMailMessage mailMessage=new SimpleMailMessage();
mailMessage.setFrom("1062273622@qq.com");//发起者
mailMessage.setTo(to);//接受者
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
mailSender.send(mailMessage);
System.out.println("发送简单邮件");
}catch (Exception e){
System.out.println("发送简单邮件失败");
}
}
}
6.写定时任务:每天9点发送一份电子邮件
@Service
//@Async
public class TaskService {
@Autowired
private MailService mailService;
@Scheduled(cron = "0 0 9 ? * *")
public void proces(){
mailService.sendMail("815835155@qq.com","简单邮件","lalalalalalalaal");
System.out.println("111");
}
}
时间可以修改(https://www.cnblogs.com/linjiqin/archive/2013/07/08/3178452.html)
注意:有时候会报错找不到mailSender
解决的方法是:添加一个依赖包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>```