java TimerTask定时调度

java利用Timer和TimerTask进行定时调度时,如果碰到TimerTask的任务执行时间多于定时调度的时间频率则会出现延迟状况,所以在TimerTask的run方法中通过开辟线程的方法来对任务进行处理,减少了时间延迟带来的误差

1. [代码]每次调度信息都会被显示在控制台和被写到文件里面,可以直接看控制台的数据也可以到文件上去查看信息 


package timer;
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
 
import thread.EventRunnable;
import file.TxtFileUtil;
 
public class RunTimerTask extends TimerTask {
     // 标记第几次调度
     public static int num = 1 ;
     File file = new File(
             "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt" /** 文件路径名 **/
     );
 
     @Override
     public void run() {
         // TODO Auto-generated method stub
         // 标记开始时间
         double startTime = System.currentTimeMillis();
         System.out.println( "start" );
 
         /**
          * 每次调用将日期存入文件中
          */
         Date date = new Date();
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                 "yyyy-MM-dd HH:mm:ss" );
         String stringDate = simpleDateFormat.format(date);
 
         TxtFileUtil.appendToFile(stringDate + "\r\n" , file); // \r\n实现换行,不能对换位置
 
         /**
          * 每次执行一个时间调度任务时都开辟一个线程去执行,这样可以减少时间开销避免任务执行时间过长导致定时调度的延迟
          */
         EventRunnable eventRunnable = new EventRunnable( "event" + num);
         Thread thread = new Thread(eventRunnable);
         thread.start();
 
         
         
         /**
          * 算出执行完run方法后消耗的总时间,如果超过一秒则定时器将延迟
          */
         double endTime = 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();
 
         }
         
     }
 
}
 
 
package thread;
 
import java.io.File;
 
import file.TxtFileUtil;
 
public class EventRunnable implements Runnable {
     private String name;
     File file = new File(
             "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt" /** 文件路径名 **/
     );
 
     public EventRunnable(String name) {
         super ();
         this .name = name;
     }
 
     @Override
     public void run() {
         // TODO Auto-generated method stub
         
         double startTime = System.currentTimeMillis();
         String x = "nihao" ;
         for ( int i = 0 ; i < 80000 ; i++) {
             x += "!" ;
         }
         double endTime = System.currentTimeMillis();
 
         System.out.println(name + ":" + (endTime - startTime) + "毫秒" );
         TxtFileUtil.appendToFile(name + ":" + (endTime - startTime) + "毫秒"
                 + "\r\n" , file);
     }
 
}
 
 
package timer;
 
import java.io.File;
 
import file.TxtFileUtil;
 
import java.io.ObjectInputStream.GetField;
import java.sql.Time;
import java.util.Timer;
 
public class testTimeTast {
 
     public static void main(String[] args) {
     
         // 新建一个文件
         File file = new File(
                 "C:\\Users\\Administrator.BGQJFNVC3FDF6KO\\Desktop\\14.txt" /**
          *
          * 文件路径名
          **/
         );
         try {
             TxtFileUtil.createFile(file);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         /**
          * 新建一个时间调度任务
          */
         RunTimerTask run = new RunTimerTask();
 
         Timer timer = new Timer();
         // 每隔一秒钟执行任务一次,但是如果RunTimerTask执行时间超过一秒了,则会出现延迟的状况
         timer.schedule(run, 0 , 1000 );
 
     }
 
}
 
 
package file;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
 
/**
  *
  * @author nyc
  *
  *         用于读写txt文件的工具类
  */
public class TxtFileUtil {
 
     /**
      * 创建文件
      *
      * @param txtFile
      * @return
      */
     public static boolean createFile(File txtFile) throws Exception {
         boolean flag = false ;
         try {
             if (!txtFile.exists()) {
                 txtFile.createNewFile();
                 flag = true ;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return flag;
     }
 
     /**
      * 读TXT文件内容
      *
      * @param txtFile
      * @return
      */
     public static String readTxtFile(File txtFile) throws Exception {
         String result = "" ;
         FileReader fileReader = null ;
         BufferedReader bufferedReader = null ;
         try {
             fileReader = new FileReader(txtFile);
             bufferedReader = new BufferedReader(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();
             }
         }
         return result;
     }
 
     public static boolean compareFiles(File srcFile, File desFile) {
 
         return getFileMD5(srcFile).equals(getFileMD5(desFile));
         
     }
     
     private static String getFileMD5(File file) {
         if (!file.isFile()){
           return null ;
         }
         MessageDigest digest = null ;
         FileInputStream in= null ;
         byte buffer[] = new byte [ 1024 ];
         int len;
         try {
           digest = MessageDigest.getInstance( "MD5" );
           in = new FileInputStream(file);
           while ((len = in.read(buffer, 0 , 1024 )) != - 1 ) {
             digest.update(buffer, 0 , len);
           }
           in.close();
         } catch (Exception e) {
           e.printStackTrace();
           return null ;
         }
         BigInteger bigInt = new BigInteger( 1 , digest.digest());
         return bigInt.toString( 16 );
       }
     
     /**
      * 追加到内容到原文件尾部
      *
      * @param txtFile
      */
 
     public static boolean appendToFile(String content, File txtFile) {
         boolean append = false ;
         boolean result = false ;
 
         try {
             if (txtFile.exists())
                 append = true ;
             FileWriter fw = new FileWriter(txtFile, append); // 同时创建新文件
             // 创建字符输出流对象
             BufferedWriter bf = new BufferedWriter(fw);
             // 创建缓冲字符输出流对象
             bf.append(content);
             result = true ;
             bf.flush();
             bf.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
         return result;
     }
 
     /**
      * 将内容写到TXT文件,覆盖原来内容
      *
      * @param content
      *            :写入的符串
      * @param txtFile
      *            :文本文件
      * @return: 是否写入成功
      * @throws Exception
      *             :抛出异常
      */
     public static boolean writeTxtFile(String content, File txtFile)
             throws Exception {
         // RandomAccessFile mm = null;
         boolean flag = false ;
         FileOutputStream outStream = null ;
         try {
 
             outStream = new FileOutputStream(txtFile);
             if (txtFile.exists()) {
                 txtFile.delete();
             }
 
             outStream.write(( new String( "" )).getBytes());
             outStream.flush();
             outStream.write(content.getBytes( "utf8" ));
             outStream.close();
             flag = true ;
         } catch (Exception e) {
             e.printStackTrace();
         }
         return flag;
     }
 
     public static 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();
         }
 
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值