SpringBoot2.X
1:异步任务:
1)在需要开启异步任务的方法上添加注解:@Async
@Service public class AsyncService {
//告诉Spring这是一个异步方法 @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("处理数据中..."); } }
|
2)在启动主类上开启异步注解: @EnableAsync
@EnableAsync //开启异步注解功能 @SpringBootApplication public class Springboot04TaskApplication {
public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } }
|
2:定时任务
1)在需要开启定时任务的方法上添加注解:@Scheduled
@Service public class ScheduledService {
/** * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几). * 0 * * * * MON-FRI * 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次 * 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次 * 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次 * 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次 * 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次; */ // @Scheduled(cron = "0 * * * * MON-SAT") //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT") // @Scheduled(cron = "0-4 * * * * MON-SAT") @Scheduled(cron = "0/4 * * * * MON-SAT") //每4秒执行一次 public void hello(){ System.out.println("hello ... "); } }
|
2)在启动主类上开启定时注解:@EnableScheduling
@EnableAsync //开启异步注解功能 @EnableScheduling //开启基于注解的定时任务 @SpringBootApplication public class Springboot04TaskApplication {
public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } }
|
3:邮件任务
1)添加mail模块依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
|
2)添加相关配置
#邮箱账号 spring.mail.username=534096094@qq.com #不是个人的邮箱密码,而是第三方服务器生成的授权码 spring.mail.password=gtstkoszjelabijb #邮箱服务器地址 spring.mail.host=smtp.qq.com #安全相关的配置需要开启 spring.mail.properties.mail.smtp.ssl.enable=true
|
3)注入 JavaMailSenderImpl 进行测试
@RunWith(SpringRunner.class) @SpringBootTest public class Springboot04TaskApplicationTests {
@Autowired JavaMailSenderImpl mailSender;
@Test public void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); //邮件设置 message.setSubject("通知-今晚开会"); message.setText("今晚7:30开会");
message.setTo("17512080612@163.com"); message.setFrom("534096094@qq.com");
mailSender.send(message); }
@Test public void test02() throws Exception{ //1、创建一个复杂的消息邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//邮件设置 helper.setSubject("通知-今晚开会"); helper.setText("<b style='color:red'>今天 7:30 开会</b>",true);
helper.setTo("17512080612@163.com"); helper.setFrom("534096094@qq.com");
//上传文件 helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));
mailSender.send(mimeMessage);
}
}
|