使用SpringBoot中的Schedule定时发送邮件的方法
作者:DaenCode
在SpringBoot中,你可以使用@Scheduled注解来创建定时任务,@Scheduled注解可以应用于方法上,表示这个方法是一个定时任务,可以根据指定的时间间隔或固定时间执行,本文就给大家介绍一下如何使用SpringBoot中的Schedule定时发送邮件,需要的朋友可以参考下
思维导图

介绍
- 基本概念:定时任务从字面不难看出,定时任务意思就是定时处理某种任务。
- 使用场景:比如说定时发送邮件、消息提醒等等。
- 常见的定时任务:Java.util.TImer、Quartz2、SpringBoot中的Schedule。
本文的主要内容以springboot中的Schedule为例,来带大家看看如何使用其做定时任务。
必不可少的注解
@EnableScheduling :用于标识启动类开启定时任务。
@Component :用于标识定时任务类,让Spring扫描其为组件。
@Scheduled :用户标识在定时任务方法上,配置定时的规则。
入门案例
启动类添加@EnableScheduling
启动类添加@EnableScheduling负责开启定时任务功能。
@SpringBootApplication
@MapperScan("com.shoanjen.redis.mapper")
@EnableScheduling
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}定义定时任务类
定义定时任务类,并标注@Component注解。
定义定时任务方法并标识@Schduled注解,每隔5秒在控制台输出日志。其中@Schedule参数如下
| 参数 | 描述 |
|---|---|
cron | 指定一个Cron表达式,用于精确控制任务的执行时间 |
zone | 指定用于解析Cron表达式的时区,默认为服务器的默认时区 |
fixedDelay | 指定任务结束后的延迟时间(毫秒),用于控制下一次任务执行的间隔 |
fixedDelayString | 与fixedDelay类似,但可以使用字符串表示延迟时间 |
fixedRate | 指定任务开始执行后的间隔时间(毫秒),用于控制连续任务之间的间隔 |
fixedRateString | 与fixedRate类似,但可以使用字符串表示间隔时间 |
initialDelay | 指定任务首次执行前的延迟时间(毫秒) |
initialDelayString | 与initialDelay类似,但可以使用字符串表示延迟时间 |
有关于Cron表达式的配置可以参考此网址:Cron小工具

@Component
public class ScheduleService {
@Scheduled(fixedRate = 5000)
//@Scheduled(fixedDelay = 5000)
public void scheduleConsole(){
System.out.println("定时任务要开始了哟!!!!");
}
}效果

定时发送邮件
引入相关依赖
<!-- Spring Mail依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>126邮箱配置
1.开启POP3/SMTP服务


2.点击开启后,会发送短信获取授权码,注意要保存授权码只显示一次!!!!

修改项目配置文件
spring.mail.host=smtp.126.com spring.mail.username=XXXXXX@126.com spring.mail.password=这里就是你刚刚的授权码哟!
编写定时任务方法
在这里就举一个简单的发送验证码例子来进行演示。下方类中的定时任务方法用来 每天21:34定时向邮件发送验证码的功能 。
@Component
public class ScheduleService {
@Autowired
private JavaMailSender mailSender;
@Scheduled(cron = "0 34 21 * * ?")
public void scheduleMailTo(){
SimpleMailMessage message = new SimpleMailMessage();
//随机验证码
Random random=new Random();
int code=random.nextInt(9999)+1;
// 发件人,配置文件中的邮件地址
message.setFrom("xxxxx@126.com");
// 收件人
message.setTo("xxxxx@163.com");
//设置邮件标题
message.setSubject("注册验证码");
// 邮件内容
message.setText("Hello欢迎使用xxx系统,您的注册验证码为"+code);
mailSender.send(message);
System.out.println("邮件发送已完成哦!!!");
}
}最终效果
最终效果请查看红框!

写在最后
有关于SpringBoot中Schedule定时任务的方法到此就结束啦,希望对阅读本文的你们有帮助哦。同时有疑问可以在评论区留言,谢谢大家!
以上就是使用SpringBoot中的Schedule定时发送邮件的方法的详细内容,更多关于SpringBoot Schedule定时发送邮件的资料请关注脚本之家其它相关文章!
