任务

1、异步任务
开启

@SpringBootApplication
@EnableAsync
public class Demo14Application {

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

}

使用

    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

2、邮件任务
依赖

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

配置

spring.mail.username=2530942753@qq.com
spring.mail.password=seamfpgsfjthdhgc
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

使用

@Test
    void contextLoads() {
        //发送一个简单的邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("Yan");
        simpleMailMessage.setText("hello Yan");
        simpleMailMessage.setFrom("2530942753@qq.com");
        simpleMailMessage.setTo("2530942753@qq.com");
        mailSender.send(simpleMailMessage);
    }
    @Test
    void contextLoads1() throws MessagingException {
        //发送一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("Yan");
        helper.setText("hello Yan");
        helper.setFrom("2530942753@qq.com");
        helper.setTo("2530942753@qq.com");
        helper.addAttachment("20201022160116.png", new File("C:\\Users\\Alex Mercer\\Desktop\\20201022160116.png"));
        mailSender.send(mimeMessage);
    }

3、定时任务
TaskExecutor
TaskScheduler
开启

@SpringBootApplication
@EnableScheduling
public class Demo14Application {

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

}

使用

@Service
public class HelloService {
    @Scheduled(cron = "0/2 * * * * ?")
    public void hello(){
        System.out.println("hello");
    }
}
posted @   max_yan  阅读(144)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示