I have a task which I need to run every 6 AM in the morning. I have my below code which does the job and it is using ScheduledExecutorService
.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int delayInHour = hour < 6 ? 6 - hour : 6 - hour + 24;
System.out.println("Current Hour: "+hour);
System.out.println("Commuted Delay for next 6 AM: "+delayInHour);
scheduler.scheduleAtFixedRate(new MyTask(), delayInHour, 24, TimeUnit.HOURS);
Problem Statement:-
With the above code, suppose if I run it now, then it will execute MyTask()
in the 6 AM in the morning. But what I need to do is, whenever I am running my program for the first time, then it should execute MyTask() instantly and next run should happen at 6 AM in the morning.
Is it possible to achieve with the above code?