SpringBoot定时任务(以发送邮件为例)

 

  • pom添加依赖:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-mail</artifactId> 
</dependency>
  • properties配置

#mail 
spring.mail.host=smtp.163.com 
spring.mail.username=xxxx@163.com 
#163的授权码 
spring.mail.password=xxxx
spring.mail.default-encoding=UTF-8
  • 发送邮件工具类:

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.mail.MailException; 
import org.springframework.mail.SimpleMailMessage; 
import org.springframework.mail.javamail.JavaMailSender; 
import org.springframework.stereotype.Component; 
@Component 
public class MailServiceUtils{ 
    private final Logger logger = LoggerFactory.getLogger(this.getClass()); 
    @Autowired 
    private JavaMailSender mailSender; 
/** 
 * @param from 发送人 
 * @param to 接收人 
 * @param subject 主题 
 * @param content 内容 
*/ 
    public void sendMail(String from,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 (MailException e) { 
        logger.error("发送邮件错误:",e); 
        } 
    } 
}

  • 启动类添加注解定时任务注解@EnableScheduling

  • 测试使用

public class Test { 
    int i = 0;
    @Resource
    private MailServiceUtils mailServiceUtils;
    @Scheduled(fixedRate = 4000)//定时任务4秒执行一次
    //@Scheduled(cron="0/4 * *  * * ? "),cron表达式,同样表示每4秒执行一次
    public void test(){
    mailServiceUtils.sendMail("from_user@163.com","to_user@qq.com","主题"+i,"你好鸭!");
    i++;
    }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值