有的時候我們需要每隔一段時間去執行某個任務,在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);
}
}
程式的輸出結果為:
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++