I am attempting to create a scheduled job which runs every 5 minutes from 7 AM to 22 PM everyday. For example, it should runs at 7:00, 7:05, 7:10 ... 21:55, and then it should stop at 22:00. On the next day, it runs the same schedule again and so on.
I have found this example which shows how to use ScheduledExecutorService
to start a task at particular time.
How to run certain task every day at a particular time using ScheduledExecutorService?
I referred to the answer and write my code like below: (I am using Java 7)
class Scheduler {
private ScheduledExecutorService executors;
public static void main(String[] arg) {
Runnable task = new Runnable() {
@Override
public void run() {
...DO SOMETHING...
}
};
// Get how many seconds before the next start time (7AM).
long initDelay = getInitialDelay(7);
ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
executors.scheduleAtFixedRate(task, initDelay, (60 * 5), TimeUnit.SECONDS);
}
private static long getInitialDelay(int hour) {
Calendar calNow = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
long diff = cal.getTimeInMillis() - calNow.getTimeInMillis();
if (diff < 0) {
cal.add(Calendar.DAY_OF_MONTH, 1);
diff = cal.getTimeInMillis() - calNow.getTimeInMillis();
}
return diff / 1000;
}
}
My above code starts at 7 AM and runs every 5 minutes perfectly. However, how can I do to control ScheduledExecuterService
to stop the task at 22 PM and then start again at 7 AM on the next day?
Or, is there any better other way to run a task during particular period of time everyday?