定时任务引入meaven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
邮件服务引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
1.定时任务
@SpringBootApplication
@EnableScheduling
public class Application{ public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
demo1
@Component
public class SchedulerTask { private int count=0; @Scheduled(cron="*/6 * * * * ?") private void process(){ System.out.println("this is scheduler task runing "+(count++)); }
}
demo2
@Component
public class Scheduler2Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); }
}
2.邮件服务
spring.mail.host=smtp.qq.com //邮箱服务器地址
spring.mail.username=xxx@qq.com //用户名
spring.mail.password=xxyyooo //开启POP3/SMTP服务的验证码 ,具体类型邮件服务详情度娘
spring.mail.default-encoding=UTF-8
mail.fromMail.addr=xxx@oo.com //发送邮件本人
public interface MailService { void sendSimpleMail(String to,String subject,String content); }
@Component
public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } }
}
4.编写测试类进行测试
@SpringBootTest
public class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { MailService.sendSimpleMail("***@qq.com","test simple mail"," hello this is simple mail"); }
}