使用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); 

/* 在执行这个任务前等待十秒...
timer.schedule( task, 10000 );
 在执行任务前等待十秒,然后每过十秒再执行一次
timer.schedule( task, 5000, 10000 );

*/
 }
 
}

程序的输出结果为:

Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.

C:/>java TimerUse
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=33749 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值