Schedule a task every day using ScheduledExecutorService?

3.9k views Asked by At

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?

1

There are 1 answers

2
Deepak Bhatia On

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,

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Date aDate = new Date();// Current date or parsed date;

Calendar with = Calendar.getInstance();
with.setTime(aDate);
int hour = with.get(Calendar.HOUR_OF_DAY);
int Minutes = with.get(Calendar.MINUTE);

int MinutesPassed12AM = hour * 60 + Minutes;
int MinutesAt3AM = 3 * 60;
int OneDayMinutes = 24 * 60;
long DelayInMinutes = MinutesPassed12AM <= MinutesAt3AM ? MinutesAt3AM - MinutesPassed12AM : OneDayMinutes - (MinutesPassed12AM - MinutesAt3AM);


scheduler.scheduleAtFixedRate(new MyTask(), DelayInMinutes, OneDayMinutes, TimeUnit.MINUTES); 

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();.