任务

96 阅读1分钟

异步任务

@SpringBootApplication
@EnableAsync//开启异步注解功能
public class SpringbootTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTaskApplication.class, args);
    }

}
  • service
@Service
public class AsyncService {

    //告诉Spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}
  • controller
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();//停止三秒
        return "ok";
    }
}

邮件任务

  • maven
<!--javax.mail配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  • 配置文件
spring.mail.username=1823149784@qq.com
spring.mail.password=uakbcuqbfgqpeicd
spring.mail.host=smtp.qq.com
# 开启加密验证(只有qq有)
spring.mail.properties.mail.smtp.ssl.enable=true
  • controller
@Autowired
JavaMailSenderImpl javaMailSender;
//实现封装
public void sendMil(Boolean multipleFile,String text,String sender,String receiver,String subject) throws MessagingException {
    //一个复杂的邮件
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    //组装
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,multipleFile);//true开启多文件
    helper.setSubject(subject);
    helper.setText(text,true);

    //附件,最好用数组来接收HashMap
    helper.addAttachment("1.jpg",new File("C:\Users\18231\Desktop\1.jpg"));
    helper.addAttachment("2.jpg",new File("C:\Users\18231\Desktop\1.jpg"));

    helper.setTo(receiver);
    helper.setFrom(sender);

    javaMailSender.send(mimeMessage);
}

定时任务

TaskScheduler 任务调度者
TaskExecutor 任务执行者


@EnableScheduling //开启定时功能的注解
@Schedule //表示什么时候执行

Cron表达式  生成网站(https://www.bejson.com/othertools/cron/)
@SpringBootApplication
@EnableScheduling //开启定时功能的注解
@EnableAsync//开启异步注解功能
public class SpringbootTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTaskApplication.class, args);
    }

}
  • service
@Service
public class ScheduledService {

    //在一个特定的时间执行这个方法 ~Timer

    //cron表达式
    //秒 分 时 日 月 周几
    /*
    30 53 19 * * ?  每天10点15分30秒执行一次
    30 0/5 10,18 * * ?  每天10点和18点,每隔5分钟执行一次
    30 15 10 ? * 1-6  每个月的周一到周六 10点15分执行
     */
    @Scheduled(cron = "30 53 19 * * ?")
    public void hello(){
        System.out.println("hello,你被执行了");
    }
}