I have a TimerTask
object timerTask. My code is running but when service gets started initially, my timer task runs instantly before the specified time i.e. 3:30 PM, though I want it to run on 3:30 PM once per day only.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.PM);
cal.set(Calendar.HOUR, 3);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
Date date = cal.getTime();
timer.schedule(timerTask, date, 1000*60*60*24); // once per day
As other community users suggested, don't use Timertask, android has a
AlarmManager
that you can use.
HOW?
Here a Snippet as Example:
Edit:
if the time can changed dynamically in the App depending on user-inputs, then just change the Calender firingCal variable for adjusting the time.