java TimerTask定時調度

java利用Timer和TimerTask進行定時調度時,如果碰到TimerTask的任務執行時間多於定時調度的時間頻率則會出現延遲狀況,所以在TimerTask的run方法中通過開闢線程的方法來對任務進行處理,減少了時間延遲帶來的誤差

1. [代碼]每次調度信息都會被顯示在控制檯和被寫到文件裏面,可以直接看控制檯的數據也可以到文件上去查看信息 


packagetimer;
 
importjava.io.File;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.TimerTask;
 
importthread.EventRunnable;
importfile.TxtFileUtil;
 
publicclass RunTimerTask extendsTimerTask {
    // 標記第幾次調度
    publicstatic int num = 1;
    File file = newFile(
            "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt"/** 文件路徑名 **/
    );
 
    @Override
    publicvoid run() {
        // TODO Auto-generated method stub
        // 標記開始時間
        doublestartTime = System.currentTimeMillis();
        System.out.println("start");
 
        /**
         * 每次調用將日期存入文件中
         */
        Date date = newDate();
        SimpleDateFormat simpleDateFormat = newSimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String stringDate = simpleDateFormat.format(date);
 
        TxtFileUtil.appendToFile(stringDate + "\r\n", file);// \r\n實現換行,不能對換位置
 
        /**
         * 每次執行一個時間調度任務時都開闢一個線程去執行,這樣可以減少時間開銷避免任務執行時間過長導致定時調度的延遲
         */
        EventRunnable eventRunnable = newEventRunnable("event"+ num);
        Thread thread = newThread(eventRunnable);
        thread.start();
 
         
         
        /**
         * 算出執行完run方法後消耗的總時間,如果超過一秒則定時器將延遲
         */
        doubleendTime = System.currentTimeMillis();
        System.out.println("RunTimerTask"+ num+":"+ (endTime - startTime) + "毫秒");
        TxtFileUtil.appendToFile("RunTimerTask"+num + ":"+ (endTime - startTime)
                +"毫秒"+ "\r\n", file);
         
         
        // 運行十次後結束
        num++;
        while(RunTimerTask.num == 11) {
            this.cancel();
 
        }
         
    }
 
}
 
 
packagethread;
 
importjava.io.File;
 
importfile.TxtFileUtil;
 
publicclass EventRunnable implementsRunnable {
    privateString name;
    File file = newFile(
            "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt"/** 文件路徑名 **/
    );
 
    publicEventRunnable(String name) {
        super();
        this.name = name;
    }
 
    @Override
    publicvoid run() {
        // TODO Auto-generated method stub
         
        doublestartTime = System.currentTimeMillis();
        String x = "nihao";
        for(inti = 0; i < 80000; i++) {
            x += "!";
        }
        doubleendTime = System.currentTimeMillis();
 
        System.out.println(name + ":"+ (endTime - startTime) + "毫秒");
        TxtFileUtil.appendToFile(name + ":"+ (endTime - startTime) + "毫秒"
                +"\r\n", file);
    }
 
}
 
 
packagetimer;
 
importjava.io.File;
 
importfile.TxtFileUtil;
 
importjava.io.ObjectInputStream.GetField;
importjava.sql.Time;
importjava.util.Timer;
 
publicclass testTimeTast {
 
    publicstatic void main(String[] args) {
     
        // 新建一個文件
        File file = newFile(
                "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt"/**
         *
         * 文件路徑名
         **/
        );
        try{
            TxtFileUtil.createFile(file);
        }catch(Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /**
         * 新建一個時間調度任務
         */
        RunTimerTask run = newRunTimerTask();
 
        Timer timer = newTimer();
        // 每隔一秒鐘執行任務一次,但是如果RunTimerTask執行時間超過一秒了,則會出現延遲的狀況
        timer.schedule(run,0,1000);
 
    }
 
}
 
 
packagefile;
 
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.math.BigInteger;
importjava.security.MessageDigest;
 
/**
 *
 * @author nyc
 *
 *         用於讀寫txt文件的工具類
 */
publicclass TxtFileUtil {
 
    /**
     * 創建文件
     *
     * @param txtFile
     * @return
     */
    publicstatic boolean createFile(File txtFile) throwsException {
        booleanflag = false;
        try{
            if(!txtFile.exists()) {
                txtFile.createNewFile();
                flag = true;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnflag;
    }
 
    /**
     * 讀TXT文件內容
     *
     * @param txtFile
     * @return
     */
    publicstatic String readTxtFile(File txtFile) throwsException {
        String result = "";
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try{
            fileReader = newFileReader(txtFile);
            bufferedReader = newBufferedReader(fileReader);
            try{
                String read = null;
                while((read = bufferedReader.readLine()) != null) {
                    if(!read.equals("\r\n")){
                    result = result + read + "\r\n";
                    }
                    else{
                        result=result+read;
                    }
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally{
            if(bufferedReader != null) {
                bufferedReader.close();
            }
            if(fileReader != null) {
                fileReader.close();
            }
        }
        returnresult;
    }
 
    publicstatic boolean compareFiles(File srcFile, File desFile) {
 
        returngetFileMD5(srcFile).equals(getFileMD5(desFile));
         
    }
     
    privatestatic String getFileMD5(File file) {
        if(!file.isFile()){
          returnnull;
        }
        MessageDigest digest = null;
        FileInputStream in=null;
        bytebuffer[] = newbyte[1024];
        intlen;
        try{
          digest = MessageDigest.getInstance("MD5");
          in = newFileInputStream(file);
          while((len = in.read(buffer, 0,1024)) != -1) {
            digest.update(buffer,0, len);
          }
          in.close();
        }catch(Exception e) {
          e.printStackTrace();
          returnnull;
        }
        BigInteger bigInt = newBigInteger(1, digest.digest());
        returnbigInt.toString(16);
      }
     
    /**
     * 追加到內容到原文件尾部
     *
     * @param txtFile
     */
 
    publicstatic boolean appendToFile(String content, File txtFile) {
        booleanappend = false;
        booleanresult = false;
 
        try{
            if(txtFile.exists())
                append = true;
            FileWriter fw = newFileWriter(txtFile, append);// 同時創建新文件
            // 創建字符輸出流對象
            BufferedWriter bf = newBufferedWriter(fw);
            // 創建緩衝字符輸出流對象
            bf.append(content);
            result = true;
            bf.flush();
            bf.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
        returnresult;
    }
 
    /**
     * 將內容寫到TXT文件,覆蓋原來內容
     *
     * @param content
     *            :寫入的符串
     * @param txtFile
     *            :文本文件
     * @return: 是否寫入成功
     * @throws Exception
     *             :拋出異常
     */
    publicstatic boolean writeTxtFile(String content, File txtFile)
            throwsException {
        // RandomAccessFile mm = null;
        booleanflag = false;
        FileOutputStream outStream = null;
        try{
 
            outStream = newFileOutputStream(txtFile);
            if(txtFile.exists()) {
                txtFile.delete();
            }
 
            outStream.write((newString("")).getBytes());
            outStream.flush();
            outStream.write(content.getBytes("utf8"));
            outStream.close();
            flag = true;
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnflag;
    }
 
    publicstatic void copyFile(File frmFile, File toFile) {
 
        String content = "";
        try{
            content = readTxtFile(frmFile);
            if(toFile.exists()) {
                toFile.delete();
            }
            writeTxtFile(content, toFile);
        }catch(Exception e) {
            e.printStackTrace();
        }
 
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章