天天看點

jdk定時任務TimerScheduledExecutorService

目錄

  • Timer
  • ScheduledExecutorService

Timer

詳情請見:

https://blog.csdn.net/xianpinjin4752/article/details/80033379

簡單使用看例子:

package com.demo;

import javax.naming.Name;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

    public static void main(String[] args) {
        //建立計時任務,實作線程接口Runnable
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "運作結束。");
            }
        };
        //建立計時器
        Timer timer = new Timer("timer-task");
        //5000毫秒以後執行
        timer.schedule(timerTask, 5000);
        //用Date來指定執行時間,1小時後
        timer.schedule(timerTask, new Date(System.currentTimeMillis()+1*60*60*1000));
        //5000毫秒後開始執行,之後每3000毫秒執行一次
        timer.schedule(timerTask, 5000, 3000);
        //用Date來指定執行時間,1小時後,每3000毫秒執行一次
        timer.schedule(timerTask, new Date(System.currentTimeMillis()+1*60*60*1000), 3000);
        //timer.scheduleAtFixedRate(),任務拖延後,把前面欠的都會補上
    }
}
           

ScheduledExecutorService

ScheduledExecutorService是一個線程池,卻有實作定時循環和延遲任務的特性。

因為Timer内部是單線程實作,一旦報錯就會停止循環任務。是以會常用ScheduledExecutorService來定時循環任務。一來是多線程實作循環任務,防止報錯中斷其他線程;二來是直接用線程實作任務執行個體,友善程式設計。

詳情參考:

https://blog.csdn.net/ma969070578/article/details/82863477

簡單了解應用,例子:

package com.demo;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest {

    public static void main(String[] args) {
        // 建立定時任務
        Runnable thread = new Runnable() {
            @Override
            public void run() {
                System.out.println("time task running. ");
            }
        };
        // 1、獲得scheduledExecutorService執行個體,下邊是建立單線程,newScheduledThreadPool是建立線程池。
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 2、定時一次性任務,5秒後執行
        scheduledExecutorService.schedule(thread, 5, TimeUnit.SECONDS);
        //定時循環任務,5秒後,每3秒循環一次,下面是一任務開始時間計算,scheduleWithFixedDelay是任務結束後開始計算周期時間(3秒)
        scheduledExecutorService.scheduleAtFixedRate(thread, 5, 3, TimeUnit.SECONDS);
    }
}