I am trying to run a certain task everyday at 5 AM in the morning. So I decided to use ScheduledExecutorService
for this but so far I have seen examples which shows how to run task every few minutes.
And I am not able to find any example which shows how to run a task every day at a particular time (5 AM) in the morning and also considering the fact of daylight saving time as well -
Below is my code which will run every 15 minutes -
public class ScheduledTaskExample {
private final ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
public void startScheduleTask() {
/**
* not using the taskHandle returned here, but it can be used to cancel
* the task, or check if it's done (for recurring tasks, that's not
* going to be very useful)
*/
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
try {
getDataFromDatabase();
}catch(Exception ex) {
ex.printStackTrace(); //or loggger would be better
}
}
}, 0, 15, TimeUnit.MINUTES);
}
private void getDataFromDatabase() {
System.out.println("getting data...");
}
public static void main(String[] args) {
ScheduledTaskExample ste = new ScheduledTaskExample();
ste.startScheduleTask();
}
}
Is there any way, I can schedule a task to run every day 5 AM in the morning using ScheduledExecutorService
considering the fact of daylight saving time as well?
And also TimerTask
is better for this or ScheduledExecutorService
?
As with the present java SE 8 release with it's excellent date time API with
java.time
these kind of calculation can be done more easily instead of usingjava.util.Calendar
andjava.util.Date
.Now as a sample example for scheduling a task with your use case:
The
initialDelay
is computed to ask the scheduler to delay the execution inTimeUnit.SECONDS
. Time difference issues with unit milliseconds and below seems to be negligible for this use case. But you can still make use ofduration.toMillis()
andTimeUnit.MILLISECONDS
for handling the scheduling computaions in milliseconds.NO:
ScheduledExecutorService
seemingly better thanTimerTask
. StackOverflow has already an answer for you.From @PaddyD,
As it is true and @PaddyD already has given a workaround(+1 to him), I am providing a working example with Java8 date time API with
ScheduledExecutorService
. Using daemon thread is dangerousNote:
MyTask
is an interface with functionexecute
.ScheduledExecutorService
, Always useawaitTermination
after invokingshutdown
on it: There's always a likelihood your task is stuck / deadlocking and the user would wait forever.The previous example I gave with Calender was just an idea which I did mention, I avoided exact time calculation and Daylight saving issues. Updated the solution on per the complain of @PaddyD