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);
}
}
新聞熱點
疑難解答