java的timertask_Java中Timer和TimerTask来实现计时器循环触发
package xian;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
private Timer timer; ?//計時器
public TimerTest(){
timer=new Timer();
}
private TimerTask task=new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
BufferedReader read=new BufferedReader(new FileReader("C://123.txt"));
String text=null;
while((text=read.readLine())!=null){
System.out.println(text);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void start(int delay,int internal){
timer.schedule(task, delay*1000, internal*1000); //計時 ? ? ? 開始。調用TimerTask的run()
// task為是 TimerTask 類,在包:import java.util.TimerTask .使用者要繼承該類,并實現 public void run() 方法,因為 TimerTask 類實現了 Runnable 接口。
//delay為延遲。0表示無延遲 ?1000為1秒延遲
//internal為多少 毫秒
}
public static void main(String[] args) {
TimerTest test=new TimerTest();
test.start(1, 3); ?//3秒運行一次
}
}
C:/123.txt文件內容如下:
hello world
beijing
basketball
java
c/c++
運行后內容如下:
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++
總結
以上是生活随笔為你收集整理的java的timertask_Java中Timer和TimerTask来实现计时器循环触发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试前一些非技术注意事项--程序员面试金
- 下一篇: 渗透工程师日常探测漏洞全流程 初学者必看