总结:主要解决了timer重复启动关闭报错的问题,timer使用cancel()销毁时并未真正销毁,内部存在某个对象未改变,在启动时又验证了这个对象所以总会报还存在的错误。
这里自定义一个flag字段判断,并且使用单例模式,简单好用
TaskService timertask = TaskService.getInstance();
timertask.start();//启动
timertask.destroyed();//关闭
public class TaskService extends TimerTask{
private DbSvr dbsvr = DbSvr.getDbService(null);
private Timer timer = null;
private static boolean flag = false;
private static TaskService taskService;
private TaskService(){
}
public static TaskService getInstance(){
if (taskService==null || flag == true){
taskService = new TaskService();
if (flag == true)
flag = false;
}
return taskService;
}
public void start() {
if(timer == null){
timer = new Timer();
}else{
timer.purge();
}
//定时周期为5秒
timer.schedule(this,new Date(),5000);
}
public void run() {
}
public void destroyed(){
if(timer != null){
timer.cancel();
flag = true;
}
}
}