schedule vs scheduleAtFixedRate

區分二者的最好方法是 timer的啓示時間設置一個過去的時間T,scheduleAtFixedRate會把從T到現在的任務全部執行,schedule只會從現在開始計時執行並任務。


public class HelloMain {

    private static int count = 0;

    public static void main(String[] args) {

        Date date = new Date(System.currentTimeMillis() - 3000);

        Timer timer = new Timer();

        System.out.println("timer schedule before");
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                count++;
                System.out.println(count + " timer task run " + Calendar.getInstance().getTime());

            }
        }, date, 1000);
        System.out.println("timer schedule after");

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

        System.out.println("timer cancel before");
        timer.cancel();
        System.out.println("timer cancel after");
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章