1、定时任务

1、cron 表达式

语法:秒分时日月周年(Spring 不支持)
http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html
image.png

2、特殊字符:

  • ,:枚举;
    • (cron=”7,9,23 ?”):任意时刻的7,9,23 秒启动这个任务;
  • -:范围:
    • (cron=”7-20 ?”):任意时刻的7-20 秒之间,每秒启动一次
  • *:任意;
    • 指定位置的任意时刻都可以
  • /:步长;
    • (cron=”7/5 ?”):第7 秒启动,每5 秒一次;
    • (cron=”/5 * ?”):任意秒启动,每5 秒一次;
  • ?:(出现在日和周几的位置):为了防止日和周冲突,在周和日上如果要写通配符使用?
    • (cron=” 1 ?”):每月的1 号,启动这个任务;
  • L:(出现在日和周的位置)”,
    • last:最后一个
    • (cron=” ? 3L”):每月的最后一个周二
  • W:
    • Work Day:工作日
    • (cron=” W ?”):每个月的工作日触发
    • (cron=” LW ?”):每个月的最后一个工作日触发
  • :第几个

    • (cron=” ? 5#2”):每个月的第2 个周4

      3、cron 示例

      image.pngimage.pngimage.png

      4、Spring整合

  • 定时任务使用注解

    • @EnableScheduling
    • @Scheduled
  • Spring中6位组成,不允许第七位的年
  • 在周几的位置1-7代表周一到周日
  • 定时任务不应该阻塞。默认是阻塞的
    • 可以让业务运行以异步的方式,自己提交到线程池
      • CompletableFuture.runAsync(() -> {
        * },execute);
    • 支持定时任务线程池;设置 TaskSchedulingProperties spring.task.scheduling.pool.size: 5
      • 不太好使
    • 让定时任务异步执行
      • 异步任务
        • @EnableAsync
        • @Async
      • 异步配置
        • TaskExecutionAutoConfiguration
        • 通过spring.task.execution进行配置
  • 使用异步任务 + 定时任务来完成定时任务不阻塞的功能 ```java @Slf4j @Component public class HelloScheduled {
  1. @Async
  2. @Scheduled(cron = "* * * * * ?")
  3. public void hello(){
  4. log.info("每秒打印");
  5. }

}


- 主启动添加
```java
@EnableAsync
@EnableScheduling
public class MallSearchApplication {

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

}