SpringBoot异步任务、邮件、定时任务

it2024-05-11  45

一、SpringBoot开启异步任务

1.在Application启动类上方加入注解:@EnableAsync

@EnableAsync @SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }

2.在方法上加入注解:@Async

 

二、SpringBoot发送邮件

1.导入依赖

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

2.在application.properties中加入相关配置

spring.mail.username=xxxx2qq.com spring.mail.password=XXXXXXXX spring.mail.host=smtp.qq.com #开启加密验证 spring.mail.properties.mail.stmp.ssl.enable=true

3.构造邮件

@RequestMapping("/send") public String sendEmail() throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); //组装 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); //主题 helper.setSubject("xxxxxx"); helper.setText("<p style='color:red'>xxxxxxx</p>",true); //附件 pathname:路径 helper.addAttachment("1.jpg",new File("")); //发送方 helper.setFrom("xxxxxx@qq.com"); //收件方 helper.setTo("xxxxx@qq.com"); mailSender.send(mimeMessage); return "OK"; }

 三、定时任务

1.在启动类上加上注解@EnableScheduling

@EnableScheduling

2.在方法上加上注解:@Scheduled(cron = "* * * * * *")

@Scheduled(cron = "* * * * * *")

cron表达式:详见https://www.bejson.com/othertools/cron/

     秒    分    时           日    月    周几(数字0和7都代表周日)      30    15    10           *      *       ?     每天10点15分30执行一次      30    0/5   10,18   *      *       ?     每天10点和18点,每隔5分钟执行一次       0     15    10           ?    *     1-6     每个月的周一到周六的10点15分执行一次

常用表达式例子

  (1)0/2 * * * * ?   表示每2秒 执行任务

  (1)0 0/2 * * * ?    表示每2分钟 执行任务

  (1)0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务

  (2)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业

  (3)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作

  (4)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点 

  (5)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时 

  (6)0 0 12 ? * WED    表示每个星期三中午12点 

  (7)0 0 12 * * ?   每天中午12点触发 

  (8)0 15 10 ? * *    每天上午10:15触发 

  (9)0 15 10 * * ?     每天上午10:15触发 

  (10)0 15 10 * * ?    每天上午10:15触发 

  (11)0 15 10 * * ? 2005    2005年的每天上午10:15触发 

  (12)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发 

  (13)0 0/5 14 * * ?    在每天下午2点到下午2:55期间的每5分钟触发 

  (14)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 

  (15)0 0-5 14 * * ?    在每天下午2点到下午2:05期间的每1分钟触发 

  (16)0 10,44 14 ? 3 WED    每年三月的星期三的下午2:10和2:44触发 

  (17)0 15 10 ? * MON-FRI    周一至周五的上午10:15触发 

  (18)0 15 10 15 * ?    每月15日上午10:15触发 

  (19)0 15 10 L * ?    每月最后一日的上午10:15触发 

  (20)0 15 10 ? * 6L    每月的最后一个星期五上午10:15触发 

  (21)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发 

  (22)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

最新回复(0)