1.pom文件
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.SpringBootApplication入口
@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SpringbootAysncApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAysncApplication.class, args);
}
}
3.异步任务
@Service public class AsyncService { //告诉Spring这是一个异步方法 @Async public void hello(){ try { // new Thread( // ()->{ // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // ).start(); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } System.out.println("处理数据中"); } }
4.定时任务
@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 * * * * *") //每4秒执行一次 public void hello(){ System.out.println("hello ... "); } }
5.邮件任务
配置文件: spring: mail: username: 1039416911@qq.com password: zmbfwjvppwqobbfa host: smtp.qq.com # properties: # mail: # stmp: # ssl: # enable: true 测试类: @SpringBootTest class SpringbootAysncApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void test1() { SimpleMailMessage message = new SimpleMailMessage(); //邮件设置 message.setSubject("通知-今晚开会"); message.setText("今晚7:30开会"); message.setTo("wuweimou@aliyun.com"); message.setFrom("1039416911@qq.com"); mailSender.send(message); } @Test void test2() throws MessagingException { //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("1522880911@qq.com"); helper.setFrom("1039416911@qq.com"); //上传文件 helper.addAttachment("1.gif",new File("C:\\Users\\ASUS\\Desktop\\微信图片_20200223192607.gif")); helper.addAttachment("2.jpg",new File("C:\\Users\\ASUS\\Desktop\\微信图片_20200223192642.jpg")); mailSender.send(mimeMessage); } }
原文:https://www.cnblogs.com/amaocc/p/12353932.html