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
?
I had a similar problem. I had to schedule bunch of tasks that should be executed during a day using
ScheduledExecutorService
. This was solved by one task starting at 3:30 AM scheduling all other tasks relatively to his current time. And rescheduling himself for the next day at 3:30 AM.With this scenario daylight savings are not an issue anymore.
Java8:
My upgrage version from top answer:
You can use a simple date parse, if the time of the day is before now, let's start tomorrow :
If you don't have the luxury of being able to use Java 8, the following will do what you need:
It doesn't require any external libs, and will account for daylight savings. Simply pass in the time of day you want to run the task as a
Calendar
object, and the task as aRunnable
. For example:N.B. the timer task runs in a Daemon thread which is not recommended for doing any IO. If you need to use a User thread, you will need to add another method which cancels the timer.
If you have to use a
ScheduledExecutorService
, simply change thestartTimer
method to the following:I am not sure of the behaviour but you may need a stop method which calls
shutdownNow
if you go down theScheduledExecutorService
route, otherwise your application may hang when you try to stop it.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
initalDelay
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
The following example work for me
reference: https://chynten.wordpress.com/2016/06/03/java-scheduler-to-run-every-day-on-specific-time/