I am using ScheduledExecutorService
to run a particular task at 3 AM
in the morning everyday. Now I am not sure whether my below code will call MyTask()
every 3 AM
in the morning? As I am not sure whether my logic is right or not
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Date aDate = ......// Current date or parsed date;
Calendar with = Calendar.getInstance();
with.setTime(aDate);
int hour = with.get(Calendar.HOUR);
int intDelayInHour = hour < 3 ? 3 - hour : 24 - (hour - 3);
scheduler.scheduleAtFixedRate(new MyTask(), intDilayInHour, 24, TimeUnit.HOURS);
And to test this out, I need to wait for one day to see if it is working out and I don't want to do that.
Can anyone help me to identify whether my above code is right or not?
Your code is also right but the problem is that the error window in you case is +-59 Minutes and +-59 seconds i.e. your tasks can be scheduled to run between 3.00 AM to 4.00 AM but if you want to more accurate then try this,
EDIT If you look at the [Daylight saving time])http://en.wikipedia.org/wiki/Daylight_saving_time) you can see in how many countries this daylight saving is used and in daylight saving the clocks are adjusted maximum +-1 hour and that too only twice in a year, and then too if your task is so robust that it should adjust to this change then you can adjust to this change by re-invoking the above mentioned code and shutdown previous scheduler by
scheduler.shutdown();
.