springboot-任务
2020-02-24 本文已影响0人
桑鱼nicoo
使用向导快速创建springboot,其他步骤可参考之前的文章
异步任务 @EnableAsync, @Async
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
@EnableAsync // 开启异步注解 功能
@SpringBootApplication
public class MySpringBootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootTaskApplication.class, args);
}
}
@Service
public class AsyncService {
/**
* @Async 告诉spring这是一个异步方法 spring会开启一个线程池
*/
@Async
public void hello(){
try{
Thread.sleep(3000);
System.out.println("end...");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
定时任务 @EnableScheduling, @Scheduled
@Service
public class ScheduleService {
/**
* second,minute,hour,day of month(日),month,day of week(周几)
* 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 2-4 ? * 1#1 每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次
*
*/
@Scheduled(cron = "0/4 * * * * MON-SAT") //周一到周日 每4秒执行一次
public void hello(){
System.out.println("hello");
}
}
@EnableScheduling // 开启基于注解的定时任务
@EnableAsync // 开启异步注解 功能
@SpringBootApplication
public class MySpringBootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootTaskApplication.class, args);
}
}
@RestController
public class AsyncController {
@Autowired
ScheduleService scheduleService;
@GetMapping("/hello")
public String hello(){
scheduleService.hello();
return "success";
}
}
邮件任务
// pom.xml 注入依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
开启邮箱的POP3/SMTP服务 (如何使用 Foxmail 等软件收发邮件?)
image.png// application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=935789914@qq.com
spring.mail.password=jmorsvzgrvfvbecb
spring.mail.properties.mail.smtp.ssl.enable=true
@SpringBootTest
class MySpringBootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("通知");
message.setText("今天是个特别的日子");
message.setTo("935789914@qq.com");
message.setFrom("935789914@qq.com");
mailSender.send(message);
}
@Test
void test02() throws MessagingException {
//1. 创建一个复杂的消息邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
//2. 邮件设置
helper.setSubject("通知");
helper.setText("<p style=\"color:red;\">今天 7:30 开会</p>",true);
helper.setTo("935789914@qq.com");
helper.setFrom("935789914@qq.com");
helper.addAttachment("sunset-above-mount-st-michael.jpg",new File("/Users/pengyapan/Downloads/PICTURE/sunset-above-mount-st-michael.jpg"));
mailSender.send(mimeMessage);
}
@Test
void test03(){
System.out.println("\"color:red\"");
}
}