现在的位置: 首页 > 综合 > 正文

使用Java中的Timer和TimerTask

2013年10月06日 ⁄ 综合 ⁄ 共 1650字 ⁄ 字号 评论关闭

使用Java中的Timer和TimerTask
 
-----------------------------------------------------------------------
-
 
   有的时候我们需要每隔一段时间去执行某个任务,在Java中提供了Timer and TimerTask来完成这个任务,本文提供一个应用程序的源代码告诉你如何使用这两个类。
   Timer和TimerTask的方法很少,使用起来也非常方便。希望假如碰到问题参考一下API doc,里面写的很清楚。TimerTask是个抽象类,他扩展了Object并实现了Runnable接口,因此你必须在自己的Task中实现public void run()方法。这也就是我们需要执行的具体任务。Timer实际上是用来控制Task的,他提供的主要方法是重载的schedule()方法。我们这里将使用schedule(TimerTask task,long time,long internal)方法来说明如何使用它。

   下面直接提供给用程序的源代码,有得时候感觉说的太多,对初学者作用并不是很大。但是当把代码给他们看了以后,很轻易就接受了。下面我要完成的任务就是每隔3秒钟从一个文件中把内容读出来并打印到控制台,文件的内容如下:
ming.txt
hello world
beijing
basketball
java
c/c++
    这里涉及到一些IO的知识,但并不复杂。我们使用BufferedReader从文件里面读取内容,一行一行的读取,代码如下:

   try
   {
    BufferedReader br = new BufferedReader(new FileReader("ming.txt"));
    String data = null;
    while((data=br.readLine())!=null)
    {
     System.out.println(data);
    }
   }
   catch(FileNotFoundException e)
   {
    System.out.println("can not find the file");
   }
   catch(IOException e)
   {
    e.printStackTrace();
   }
在主程序中我们启动timer让他开始执行读取文件的工作。整个程序的内容如下
import java.util.*;
import java.io.*;

public class TimerUse
{
 public static void main(String[] args)
 {
  PickTask pt = new PickTask();
  pt.start(1,3);
 }
}

class PickTask
{
 private Timer timer;

 public PickTask()
 {
  timer = new Timer();
 }
 
 private TimerTask task = new TimerTask()
 {
  public void run()
  {
  
   try
   {
    BufferedReader br = new BufferedReader(new FileReader("ming.txt"));
    String data = null;
    while((data=br.readLine())!=null)
    {
     System.out.println(data);
    }
   }
   catch(FileNotFoundException e)
   {
    System.out.println("can not find the file");
   }
   catch(IOException e)
   {
    e.printStackTrace();
   }
  
  }
 };
 
 public void start(int delay,int internal )
 {
  timer.schedule(task,delay*1000,internal*1000);
 }
 
}

 

抱歉!评论已关闭.