I want to run a task at a specific time say at 7.11pm everyday. I have tried the following piece of code but it is not working.
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
System.out.println(new Date());
System.out.println("Hello !!");
}
};
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
calendar.set(Calendar.HOUR, 18);
calendar.set(Calendar.MINUTE, 11);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, calendar.getTimeInMillis(), 5, TimeUnit.SECONDS);
}
}
In the above code, I have tried to run the schedule task starting from 7:11pm everyday with an interval of 5 seconds. But it is not behaving as I expected to be. And also If I want to do the same with another condition that the task should be executed only on specific days let's say every Tuesday and Wednesday.
Am I making some kind of mistake in calculating the initialDelay parameter of the method or something else?