Springboot实现异步任务、邮件任务、定时任务

狂神说springboot学习

一、异步任务

通过spring的两个注解实现

@Async //在异步方法上标注此注解,告诉spring这是一个异步方法
@EnableAsync //在springboot启动类中标注此注解,开启异步注解功能

@Service
public class AsynService {

    @Async
    public void AsynMethod(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据处理成功");

    }

}
@EnableAsync
@SpringBootApplication
public class SpringbootTestApplication {

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

}

二、邮件任务

邮件发送的两种方式:POP3/SMTP

导入依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

以QQ邮箱为例
在这里插入图片描述
点击开启获取授权码
在这里插入图片描述

配置

#用户名
spring.mail.username=45331533@qq.com
#授权码
spring.mail.password=akgfahplepakbghd
#授权的主机如果是163就163.com
spring.mail.host=smtp.qq.com
#QQ有特殊的加密规则 需要开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
@SpringBootTest
class SpringbootTestApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        //发送简单的邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("通知");//主题
        message.setText("好好学习,天天向上");//内容
        message.setFrom("45331533@qq.com");//发送人
        message.setTo("45331533@qq.com");//接收人

        mailSender.send(message);
    }

    @Test
    void contextLoads2() throws MessagingException {
        //发送复杂的邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        helper.setSubject("通知plus");
        helper.setText("<p style='color:red'>好好学习,天天向上plus</p>",true);

        //  附件
        helper.addAttachment("1.png",new File("C:\\Users\\86183\\Desktop\\捕获.png"));

        helper.setFrom("45331533@qq.com");
        helper.setTo("45331533@qq.com");

        mailSender.send(mimeMessage);
    }

}

在这里插入图片描述
在这里插入图片描述

三、定时任务

spring提供的两个定时任务的接口

TaskScheduler #任务调度者
TaskExecutor #任务执行者
@EnableScheduling #在springboot启动类中标注此注解,开启定时功能
@Scheduled #什么时候执行,在此注解中需要通过cron表达式来设置什么时候执行

@EnableScheduling
@SpringBootApplication
public class SpringbootTestApplication {

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

}
@Service
public class ScheduledService {

    //在一个特定的时间执行这个方法
    //cron表达式
    //秒 分 时 日 月 周
    @Scheduled(cron = "0/2 * * * * 0-7")
    public void hello(){
        System.out.println("你被执行了");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值