SpringBoot 异步任务,邮箱任务,定时任务 实现方法

异步任务:

两个地方:
1、@Async 在Service的方法上添加该注解
2、在启动类上添加@EnableAsync开启异步功能

邮件任务:

1、导入spring-boot-starter-mail 依赖jar包
2、在.properties属性文件中配置

#邮箱
spring.mail.username=452598222@qq.com
spring.mail.password=在qq邮箱设置中获取密钥
spring.mail.host=smtp.qq.com
#开启加密验证(QQ邮箱需要)
spring.mail.properties.mail.smtp.ssl.enable=true

3、引入邮箱发送实现类

@Autowired
 JavaMailSenderImpl mailSender;
public void sendMail(){

	//简单邮件协议
	SimpleMailMessage mailMessage = new SimpleMailMessage();
	mailMessage.setSubject("输入主题");
	mailMessage.setText("输入内容");
	mailMessage.setTo("接收者邮箱");
	mailMessage.setFrom("发送者邮箱");
	//使用实现类.send方法发送
	mailSender.send(mailMessage);
	
	//复杂邮件协议
	MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
    helper.setSubject("设置标题");
    //支持html标签的内容
    helper.setText("设置内容<p style='color:red'>特殊样式</p>",true);
    //附件添加
    helper.addAttachment("文件名.文件类型",new File("文件路径"));
    helper.setTo("接收者邮箱");
	helper.setFrom("发送者邮箱");
    mailSender.send(mimeMessage);
}


定时任务:

需要涉及到的:

底层接口:
TaskScheduler 任务调度者
TaskScheduler 任务执行者
使用注解:
@EnableScheduling 允许定时任务
@Scheduled 声明定时任务
cron表达式:

cron = “0 0 0/2 * * ?”
含义依次 = 秒 分 年 日 月 周几
具体可百度在线生成cron表达式
其他单位表示任意方式为 : *
周几单位表示任意方式为 :?

1、在启动类上增加允许定时任务的注解

@SpringBootApplication
@EnableScheduling
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(MobilefxrApplication.class, args);
	}

2、在Service层中增加一个定时任务,并加上声明注解

 @Scheduled(cron = "0 0 0/2 * * ?")
 @Transactional
 public void ScheduleJob(){
     //定时任务内容
     doAnyThing();
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值