异步任务
- 开启异步模式
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
2)异步服务
@Service
public class AsyncService {
//表明这是个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据ing ... ");
}
}
定时任务
1)开启定时任务
@EnableScheduling
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
2)定时任务
@Service
public class ScheduledService {
/**
* second, minute, hour, day of month, month,day of week
* 0 * * * * MON-FRI
* 这里的0为秒 表示周一到周五,每整秒触发一次
*/
@Scheduled(cron = "0 * * * * MON-FRI")//corn :
public void hello(){
System.out.println("hello ...");
}
}
3)corn表达式相关
//每当秒数为0,15,30或45时,触发一次定时任务
@Scheduled(cron="0,15,30,45 * * * * MON-FRI")
//每当秒数为15到30区间内时,每一秒触发一次定时任务
@Scheduled(cron="15-30 * * * * MON-FRI")
//0到30秒内,每5秒触发一次
@Scheduled(cron="0-30/5 * * * * MON-FRI")
//每月的最后一个周六的2点,?代表冲突匹配,L表示最后
@Schedule(cron="0 0 2 ? * 6L")
邮件任务
1)引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2)获得授权口令
3)配置发件人
spring.mail.username=2232549876@qq.com
spring.mail.password=llievdxlvlnvecab
spring.mail.host=smtp.qq.com
#spring.mail.properties.mail.smtp.ssl.enable=true
4)测试简单邮件任务
@SpringBootTest
class Springboot04TaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void testSimpleMailTask(){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("这一个邮件的Subject");
simpleMailMessage.setText("这是邮件的内容");
//simpleMailMessage.setTo("ezerbelcn@gmail.com");
//simpleMailMessage.setTo("279609625@qq.com");
simpleMailMessage.setTo("loveuebz@163.com");
simpleMailMessage.setFrom("2232549876@qq.com");
mailSender.send(simpleMailMessage);
}
}
5)带附件的邮件任务
@Test
public void testAdvMailTask() throws Exception{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setSubject("mime邮件主题");
mimeMessageHelper.setText("<b style='color:red'>今天是个好日子</b>");
mimeMessageHelper.setFrom("2232549876@qq.com");
mimeMessageHelper.setTo("loveuebz@163.com");
mimeMessageHelper.addAttachment("sky.jpg",new File("C:\\Users\\22325\\Pictures\\sky.jpg"));
mimeMessageHelper.addAttachment("paradise.jpg",new File("C:\\Users\\22325\\Pictures\\paradise.jpg"));
mailSender.send(mimeMessage);
}