I have a requirement where I need to run the Java program only between 9AM and 5PM on weekdays. Timezone will be UTC always. The program should start exactly at 9AM and should end before 5PM. If it can't complete before 5PM then it should sleep till next day 08:59:59. If the next day is Weekend then it should start on Monday.
The article difference in seconds between two dates using joda time? explains how to get difference in seconds between two predefined dates but I always want to calculate difference between next working day 9AM and current time.
I'm thinking of using Thread.sleep() by calculating the time difference between two dates. Is there a Joda Time api which I can use to calculate the time difference between two dates?
I already tried getting the current epoch and epoch of next day 9AM if its weekday, calculating the difference between these two epochs and using that value for Thread.sleep but it's little bit messy.
Below is the pseudocode which I used
getNextDayEpoch function contains if/else code to decide if it's a weekday or weekend using Determine if date is weekday/weekend java
Based on whether its weekday or weekend, I get the corresponding epoch value.
currentEpoch = getCurrentEpoch()
nextDayEpoch = getNextDayEpoch()
difference = nextDayEpoch - currentDayEpoch
try {
Thread.sleep(difference);
} catch (InterruptedException e) {
e.printStackTrace();
}
Can you please suggest any better way to do it?