TimerTask的简单定时应用

TimerTask是一线程安全的的类,他实现了Runnable线程的接口。

1.在类中继承extends TimerTas。
2.重写实现它的run()方法。
  如:

 
引用
  public calss Test_TimerTask extends TimerTask{
   private String outputPath;
   public  Test_TimerTask (){}
   public Test_TimerTask(String outputPath){
this.outputPath=outputPath;
}
   @Override
    public void run()
    {
     long systemTime=System.currentTimeMillis();//当前毫秒数
  
      File filesource=new File(this.outputPath);//读取目录
  
      File[] filelist=filesource.listFiles();//读取目录下所有的文件
  
      for (int i = 0; i < filelist.length; i++) {
File file=filelist[i];
long fileTime=file.lastModified();//文件创建时间(最后修改时间为 创建时间)
long thirtyTime=(long)30*24*60*60*1000;//30天的毫秒数

if(systemTime-fileTime>times){//如果文件创建的时间大于30天的时间   备份
    File newFile=new File(this.outputPath+"\\backup\\"+file.getName());//这里指向新的路径
   file.renameTo(newFile);根据通过重命名方法可以把文件直接移动到新的路径                                                 
             }
        }
    }
    public static void mian(string[] args){
Test_TimerTask tt=new Test_TimerTask ("E:\\test\\input\\EPG");
               Timer timer = new Timer();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:min:ss");
                Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
  //tt代表安排的任务的类,startTime开始时间,间隔时间
        timer.scheduleAtFixedRate(tt,startTime,86400);
     //timer. schedule(tt,10000L);10秒执行一次  ,没有准确的开始时间
}
 }

   这里其实应用的很多的都是现成  Runnable线程,线程是个好东西,还得以后多研究研究。

你可能感兴趣的:(线程,timertask,定时任务,run)