Java tutorial
/** * PureInfo Force * @(#)TimerUtil.java 1.0 Dec 29, 2005 * * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. * All rights reserved, see the license file. * * www.pureinfo.com.cn */ package com.pureinfo.force.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.lang.time.DateUtils; import com.pureinfo.force.exception.PureException; import com.pureinfo.force.exception.PureRuntimeException; /** * <P> * Created on Dec 29, 2005 9:29:22 AM <BR> * Last modified on Dec 29, 2005 * </P> * * @author Freeman.Hu * @version 1.0, Dec 29, 2005 * @since Force 1.0 */ public final class TimerUtil { private TimerUtil() { } private static DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); /** * @param _sTime * must be "HH:mm" format */ public static Timer scheduleEverydayAt(String _sTime, TimerTask _task) { return scheduleFrom(_sTime, DateUtils.MILLIS_PER_DAY, _task); } /** * @param _sTime * must be "HH:mm" format */ public static Timer scheduleFrom(String _sTime, long _lPeriod, TimerTask _task) { Calendar nowTime = new GregorianCalendar(); Calendar firstTime = getTimeToday(nowTime, _sTime); firstTime.setTimeInMillis(getNext(firstTime.getTimeInMillis(), nowTime.getTimeInMillis(), _lPeriod)); Timer timer = new Timer(); timer.scheduleAtFixedRate(_task, firstTime.getTime(), _lPeriod); return timer; } private static Calendar getTimeToday(Calendar _today, String _sTime) { Calendar todayTime = new GregorianCalendar(); try { todayTime.setTime(TIME_FORMAT.parse(_sTime)); } catch (ParseException ex) { throw new PureRuntimeException(PureException.INVALID_REQUEST, "time must be HH:mm TIME_FORMAT", ex); } todayTime.set(Calendar.YEAR, _today.get(Calendar.YEAR)); todayTime.set(Calendar.MONTH, _today.get(Calendar.MONTH)); todayTime.set(Calendar.DAY_OF_MONTH, _today.get(Calendar.DAY_OF_MONTH)); return todayTime; } static long getNext(long _lStart, long _lNow, long _lPeriod) { if (_lStart <= _lNow) { long lDiff = _lNow - _lStart; if (lDiff % _lPeriod == 0) return _lNow + _lPeriod; return _lStart + _lPeriod * (lDiff / _lPeriod + 1); } return _lStart; } }