使用ThreadPoolTaskScheduler.schedule會因為任務執行的時間超過觸發器間隔,而延後後序排程時間。

以下程式RUN出來會發現

 

public String scheduleTask() {

    Runnable task = () -> {

      System.out.println(Thread.currentThread().getName() + "-Scheduled task started at: " + new Date());

      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println(Thread.currentThread().getName() + "-Scheduled task resumed at: " + new Date());
    };

    taskScheduler.schedule(task, new CronTrigger("0/5 * * * * *"));

    return "Schedule task triggered successfully!";
  }
  
  
//    Task-Scheduled-1-Scheduled task started at: Wed Jul 12 15:30:10 CST 2023
//    Task-Scheduled-1-Scheduled task resumed at: Wed Jul 12 15:30:20 CST 2023
//    Task-Scheduled-2-Scheduled task started at: Wed Jul 12 15:30:25 CST 2023
//    Task-Scheduled-2-Scheduled task resumed at: Wed Jul 12 15:30:35 CST 2023
//    Task-Scheduled-1-Scheduled task started at: Wed Jul 12 15:30:40 CST 2023
//    Task-Scheduled-1-Scheduled task resumed at: Wed Jul 12 15:30:50 CST 2023

如果不希望等待前一個排程作業結束,希望時間到就執行可以加入CompletableFuture.runAsync

public String scheduleTask2() {

    Runnable task = () -> {
      
      CompletableFuture.runAsync(() -> {

        System.out.println(Thread.currentThread().getName() + "-Scheduled task started at: " + new Date());

        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "-Scheduled task resumed at: " + new Date());
      });

    };

    taskScheduler.schedule(task, new CronTrigger("0/5 * * * * *"));
    
//    ForkJoinPool.commonPool-worker-1-Scheduled task started at: Wed Jul 12 15:33:15 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task started at: Wed Jul 12 15:33:20 CST 2023
//    ForkJoinPool.commonPool-worker-3-Scheduled task started at: Wed Jul 12 15:33:25 CST 2023
//    ForkJoinPool.commonPool-worker-1-Scheduled task resumed at: Wed Jul 12 15:33:25 CST 2023
//    ForkJoinPool.commonPool-worker-1-Scheduled task started at: Wed Jul 12 15:33:30 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task resumed at: Wed Jul 12 15:33:30 CST 2023
//    ForkJoinPool.commonPool-worker-2-Scheduled task started at: Wed Jul 12 15:33:35 CST 2023
//    ForkJoinPool.commonPool-worker-3-Scheduled task resumed at: Wed Jul 12 15:33:35 CST 2023

    return "Schedule task triggered successfully!";
  }
 

 

 

arrow
arrow

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()