spring-boot使用Scheduled定时任务
1.导入邮箱依赖
<!-- 邮件依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件application.properties
#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
#邮箱号
spring.mail.username=
#授权码
spring.mail.password=
#邮件发送安全配置
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
3.编写代码
定时发送代码块
package com.xmx.day1223_scheduled.job;
import com.xmx.day1223_scheduled.util.SendMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Auther: 郑兴源
* @DateTime : 2021-12-23 上午 11:01
* @descriptoin:定时任务的代码
*/
@Component
public class MyScheduledJob {
@Autowired
private SendMailUtil mailService;
/*定时任务的方法*/
@Scheduled(cron = "0/30 * * * * ?")
public void scheduledMetgod() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("2022定时器被触发" + sdf.format(new Date()));
/*填你的测试信息*/
String to = "1223614075@qq.com";
String title = "郑兴源·先生被聘JD京东集团125K/月";
String context = "JD京东集团中级开发人员";
mailService.sendVertifyCode(to, title, context);
}
}
邮箱发送根据类
package com.xmx.day1223_scheduled.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
/**
* @create: 2022-02-21 19:28
* @author: 郑兴源
* @description:邮件发送工具
**/
@Component
public class SendMailUtil {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
Logger logger = LoggerFactory.getLogger(this.getClass());
public void sendVertifyCode(String to, String title, String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发送人
message.setTo(to); //收件人
message.setSubject(title); //邮件名
message.setText(content); //邮件内容(验证码)
mailSender.send(message);
logger.info("已经发送");
}
}
运行主类上加注解
@SpringBootApplication
@EnableScheduling//必须启动定时任务
目录结构
4. /定时任务的方法表达式/@Scheduled(cron = “0/30 * * * * ?”)
格式: cron = “* * * * * ?”
[秒] [分] [小时] [日] [月] [周] [年]
序号 说明 是否必填 允许填写的值 允许的通配符 1 秒 是 0-59 , - * / 2 分 是 0-59 , - * / 3 小时 是 0-23 , - * / 4 日 是 1-31 , - * ? / L W 5 月 是 1-12 or JAN-DEC , - * / 6 周 是 1-7 or SUN-SAT , - * ? / L # 7
cron= 0 0 8 * * ? 表示每天早上8点
5.运行结果