java中timer怎么循环_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++

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值