任务

定时任务 scheduled

quartz

  • 启动类加上 @EnableScheduling 开启定时任务,自动扫描
  • 定时任务业务类加上 @Component
    • 里面的定时执行的方法加上注解 @Sheduled(param) 定期执行一次
      1、cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
      1)crontab 工具 https://tool.lu/crontab/
      2、fixedRate: 定时多久执行一次(上一次开始执行时间点后xx秒再次执行)
      3、fixedDelay: 上一次执行结束时间点后xx秒再次执行
      4、fixedDelayString: 字符串形式,可以通过配置文件指定
  • ** 上面是串行的,有并行的方式 **

异步任务

  • 适用场景: 处理 log, 发送邮件,短信等
  • 使用
    1. 启动类啥的使用 @EnableAsync 注解开启功能,自动扫描

    2. 定义异步任务类并使用 @Component 标记组件被容器扫描,异步方法(如果需要可以在类)加上 @Async

      • 注意点:
        • 增加 Future<String> 返回结果 AsyncResult<String>("task执行完成");
        • 如果需要拿到结果 需要判断全部的 task.isDone()
  • 代码
    • 异步任务类
      @EnableAsync
      @Component
      @Async
      public class AsyncTask {
          public Future<String> task1() throws InterruptedException {
              Thread.sleep(1000);
              System.out.println("task1 finished" + System.currentTimeMillis());
              return new AsyncResult<>("wtf");
          }
      
          public Future<Integer> task2() throws InterruptedException {
              Thread.sleep(2000);
              System.out.println("task2 finished" + System.currentTimeMillis());
              return new AsyncResult<>(1111);
          }
      
          public Future<ArrayList> task3() throws InterruptedException {
              Thread.sleep(2500);
              System.out.println("task3 finished" + System.currentTimeMillis());
              return new AsyncResult<>(new ArrayList());
          }
      }
    
    • 使用异步任务
     @Test
      public void testAsync() throws InterruptedException {
          long start = System.currentTimeMillis();
          Future<String> future1 = asyncTask.task1();
          Future<Integer> future2 = asyncTask.task2();
          Future<ArrayList> future3 = asyncTask.task3();
          while (true){
              if (future1.isDone() && future2.isDone() && future3.isDone()){
                  System.out.println("任务完成");
                  break;
              }
          }
          long end = System.currentTimeMillis();
          System.out.println(end - start);  // 约等于最大等待时间,即上面的 2.5s
          while (true){
              Thread.sleep(200);
          }
      }
    
posted @ 2019-11-27 14:48  scp-166  阅读(271)  评论(0编辑  收藏  举报