使用Java中的Timer和TimerTask

xiaoxiao2022-06-12  27

有的时候我们需要每隔一段时间去执行某个任务,在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.txthello worldbeijing basketball javac/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);  } }

程序的输出结果为:Microsoft Windows XP [版本 5.1.2600](C) 版权所有 1985-2001 Microsoft Corp.

C:\>java TimerUsehello worldbeijingbasketballjavac/c++hello worldbeijingbasketballjavac/c++hello worldbeijingbasketballjavac/c++hello worldbeijingbasketballjavac/c++

转载请注明原文地址: https://www.6miu.com/read-4932220.html

最新回复(0)