Alex Alex - 8 days ago 7
Java Question

Java Timer doesn t start after midnight

In my code i m trying to write a task which should be triggered every 24 h. The first trigger should be when the timer is scheduled and then every 7 in the morning. I m using

java.util.TimerTask


I wrote something like this:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 7);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
timer.schedule(task1, today.getTime(), TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS));


It happens that the task is launched every time i run my application (as expected?)... but after midnight if i run my application the task is not triggered.

Where is the error?

thanks

Answer

Your are providing 07:00:00 of the current day (not the next day) as firstTime.

So if the time is after 7am, your firstTime is in the past. Probably this is why the task is started immediately.

If the time is "after midnight" which is probably before 7am, the firstTime is in the future. So you have to wait for 7am for the task to start.