Springboot高级(四)任务

一、异步任务

需要的注解:@Async和@EnableAsync

java的代码是同步顺序执行,当我们需要执行异步操作时我们需要创建一个新线程去执行

    @Service
	public class AsyncService {
	
		public void hello(){
	        try {
	            Thread.sleep(3000);
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
        	System.err.println("异步任务。。。");
    	}
}
    @RequestMapping("/hello")
    public String hello(){
        System.err.println("先执行代码");
        asyncService.hello();
        return "hello....";
    }

页面请求会等待返回信息,直到3秒后,接收到返回信息。

2、如何实现异步:

实现异步效果:页面请求返回信息,后台等待执行service的hello方法。

    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println("异步任务。。。");
    }
@EnableAsync
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

二、定时任务

需要的注解:@EnableScheduling和@Scheduled

在定时执行的方法上添加注解@Scheduled,再在启动器上添加@EnableScheduling

@Service
public class taskJob {

    @Scheduled(cron = "0/3 * * * * ?")
    public void saveScheduled(){
        System.err.println("定时");
    }
}
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

在这里插入图片描述

三、邮件任务

1、邮件发送需要引入spring-boot-starter-mail

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

2、添加配置信息

spring.mail.username=xxxxx@qq.com
spring.mail.password=xxxxx  第三方授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

3、编写类

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("公告通知");
        mailMessage.setText("今日停水");
        mailMessage.setTo("1513xxx@163.com");
        mailSender.send(mailMessage);
    }
	//复杂邮件(包含附件)
    @Test
    void test01() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("公告通知");
        helper.setText("<b style='color:red;'>打法是的噶啥公司大</b>", true);
        helper.setTo("15131182486@163.com");
        //上传文件
        helper.addAttachment("1.jpg", new File("url"));
        mailSender.send(mimeMessage);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值