现在的位置: 首页 > 综合 > 正文

android/java Timer 的使用

2013年02月15日 ⁄ 综合 ⁄ 共 565字 ⁄ 字号 评论关闭
public class Test {

	public static void main(String[] args) {
		Timer timer = new Timer();
		timer.schedule(new SendMsg(), 500);	//每500ms执行一次
		
		//while代码要执行你的主线程的代码,包括接受server的ACK信息
		while(true){
			//这里的延时没有意义,就是为了方便观察打印输出信息
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("I am living ! Receve server ACK and do other things");
		}
	}
}

class SendMsg extends java.util.TimerTask{

	public void run() {
		System.out.println("Send msg to server " + counter);
		//如果不够5次就在执行完一次发送后继续定时500ms后执行
		if(counter < 5){
			Timer timer = new Timer();
			timer.schedule(new SendMsg(), 500);
			counter++;
		}
	}
	
	static int counter = 0;
}

 

抱歉!评论已关闭.