Re: Timer Schedule TimerTask for same hour every day



if timer execution time is earlier then the current time then
roll one day forward.

public void scheduleTimer(int hour, int minute) {
Calendar now = new GregorianCalendar();
int hourNow = now.get(Calendar.HOUR_OF_DAY);
int minuteNow = now.get(Calendar.MINUTE);

Calendar firstExecutionDate = new GregorianCalendar();
firstExecutionDate.set(Calendar.HOUR_OF_DAY, hour);
firstExecutionDate.set(Calendar.MINUTE, minute);
firstExecutionDate.set(Calendar.SECOND, 0);
firstExecutionDate.set(Calendar.MILLISECOND, 0);
if (hour<hourNow || (hour==hourNow && minute<minuteNow)) {
//Do not execute today, first execution will be tomorrow.
firstExecutionDate.add(Calendar.DAY_OF_MONTH, 1);
}

long oneDay = 1000L * 60L * 60L * 24L;

Timer timer = new Timer();
timer.schedule(new MyTask(), firstExecutionDate.getTime(), oneDay);

}
.



Relevant Pages