|
Package com. anllin. utils;
Import java. text. DateFormat;
Import java. text. ParseException;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. concurrent. ScheduledThreadPoolExecutor;
Import java. util. concurrent. TimeUnit;
Public class ScheduleUtil
{
Private static DateFormat format ()
{
Return new SimpleDateFormat ("HH: mm: ss: SSS ");
}
Private static Date parseTime (String time) throws ParseException
{
Return format (). parse (time );
}
Private static long getOneDayMilliseconds ()
{
Return 24*60*60 * 1000L;
}
Private static long getMillisecondsInOneDayBetween (String now, String future) throws ParseException
{
Date nowDate = parseTime (now );
Date futureDate = parseTime (future );
Long nowTime = nowDate. getTime ();
Long futureTime = futureDate. getTime ();
If (futureTime> nowTime)
{
Return futureTime-nowTime;
}
Else
{
Return (futureTime + getOneDayMilliseconds ()-nowTime;
}
}
Public static void scheduleEveryday (ScheduledThreadPoolExecutor executor, Runnable command,
String executedEverydayAt) throws ParseException
{
Long initialDelay = getMillisecondsInOneDayBetween (format (). format (new Date (), executedEverydayAt );
Long period = getOneDayMilliseconds ();
Executor. scheduleAtFixedRate (command, initialDelay, period, TimeUnit. MILLISECONDS );
}
} |