说明:该定时器作用是
设定定时器首次执行的时间firstTime和执行间隔period,如firstTime=2015-3-25 9:00:00,period=24小时,若程序启动时,已经超过firstTime(2015-3-25 9:00:00),则定时器在下一个period时(2015-3-26 9:00:00)第一次执行。
TimerTask task = new TimerTask() { //匿名内部类 @Override public void run() { //TODO } }; //设置执行时间 Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH);//每天 //定制每天的9:00:00执行 calendar.set(year, month, day, 9, 0, 0); // dateSetter为制定时间 Date dateSetter = new Date(); dateSetter = calendar.getTime(); // nowDate为当前时间 Date nowDate = new Date(); // 所得时间差为,距现在待触发时间的间隔 long interval = dateSetter.getTime() - nowDate.getTime(); if(interval < 0){ calendar.add(Calendar.DAY_OF_MONTH, 1); dateSetter = calendar.getTime(); interval = dateSetter.getTime() - nowDate.getTime(); } Timer timer = new Timer(); long period = 24 * 60 * 60 * 1000L; // long period = 2 * 60 * 1000L; timer.schedule(task, interval, period);