Timer对象执行定时任务只执行一次的问题

最近在做物联网项目,用到了Socket长连接方面的技术,找了很多这方面资料,都说保持长连接的方法最常见的就是定时发送垃圾消息让客户端与服务端的网络不断开。于是用到了Timer对象来定时发送垃圾消息,可是却遇到了TimerTask只执行一次就不再运行的问题。

class  Task extends TimerTask {

		@Override
		public void run() {
			Log.d("com.xxx.xxx.service", "timertask -------- running!");
			Packet packet = new Packet();
			packet.pack("WVM|1\r\n");
			send(packet);
		}
	}

task运行部分是这样写的:

timer = new Timer(true);
		timer.schedule(new Task(), 30000);

我的本意是让task每隔30000毫秒运行一次,但仔细查看API后发现,这个方法的意思是延时多少毫秒后执行此task。

schedule(TimerTask task, long delay)的注释:Schedules the specified task for execution after the specified delay。


后来我更换成:

timer = new Timer(true);
		timer.schedule(new Task(), 5000, 30000);
运行就正常了。

schedule(TimerTask task, long delay, long period)

你可能感兴趣的:(错误记录)