java定時器,每天00:00執行任務

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Timer;

import java.util.TimerTask;

 

public class TimerDemo {

    public static void main(String[] args) throws Exception {

        //得到時間類

        Calendar date = Calendar.getInstance();

        //設置時間爲 xx-xx-xx 00:00:00

        date.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), 0, 0, 0);

        //一天的毫秒數

        long daySpan = 24 * 60 * 60 * 1000;

        //得到定時器實例

        Timer t = new Timer();

        //使用匿名內方式進行方法覆蓋

        t.schedule(new TimerTask() {

            public void run() {

                //run中填寫定時器主要執行的代碼塊

                System.out.println("定時器執行..");

                //算了,讀取文件我也加上吧

                //你沒說是文本還是文件,我都用字節流了。

                FileInputStream fis = new FileInputStream("D:\\a.txt");

                byte[] b = new byte[1024];

                int len = 0;

                while((len=fis.read(b))!=-1){

                    //讀取輸出呀呀呀呀......

                    System.out.println(new String(b,0,len));

                }

            }

        }, date.getTime(), daySpan); //daySpan是一天的毫秒數,也是執行間隔

    };

}

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