🧑💻作者名称:DaenCode
🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。
😎人生感悟:尝尽人生百味,方知世间冷暖。
📖所属专栏:SpringBoot实战
| 标题 |
|---|
| 一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码) |
| 一张思维导图带你学会Springboot创建全局异常、自定义异常 |
| 一张思维导图带你打通SpringBoot自定义拦截器的思路 |
| 28个SpringBoot项目中常用注解,日常开发、求职面试不再懵圈 |
| 一张思维导图带你学会SpringBoot、Vue前后端分离项目线上部署 |


本文的主要内容以springboot中的Schedule为例,来带大家看看如何使用其做定时任务。
@EnableScheduling:用于标识启动类开启定时任务。
@Component:用于标识定时任务类,让Spring扫描其为组件。
@Scheduled:用户标识在定时任务方法上,配置定时的规则。
启动类添加@EnableScheduling负责开启定时任务功能。
@SpringBootApplication
@MapperScan("com.shoanjen.redis.mapper")
@EnableScheduling
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| 参数 | 描述 |
|---|---|
| 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("定时任务要开始了哟!!!!");
}
}

org.springframework.boot spring-boot-starter-mail
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定时任务的方法到此就结束啦,希望对阅读本文的你们有帮助哦。同时有疑问可以在评论区留言,谢谢大家!
