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
?
In Java 8:
Have you considered using something like Quartz Scheduler? This library has a mechanism for scheduling tasks to run at a set period of time every day using a cron like expression (take a look at
CronScheduleBuilder
).Some example code (not tested):
There's a bit more work upfront, and you may need to rewrite your job execution code, but it should give you more control over how you want you job to run. Also it would be easier to change the schedule should you need to.
Just to add up on Victor's answer.
I would recommend to add a check to see, if the variable (in his case the long
midnight
) is higher than1440
. If it is, I would omit the.plusDays(1)
, otherwise the task will only run the day after tomorrow.I did it simply like this:
You can use below class to schedule your task every day particular time