Java EE 7: Get @Schedule date when set to persistent = true

In my Java EE 7 application, I created a persistent Schedule task that runs every hour. I used the @Schedule annotation.

When this task is called up, I want to perform some actions on events that have occurred from the last hour until NOW. To get NOW, I use "new date ()".

This @Schedule has a constant default attribute of β€œtrue”, which is great because if the server stops for several hours, I want to perform these tasks on restart.

The problem is that if the server was stopped within 5 hours, the task will be started 5 times, but in all executions the β€œnew date ()” will be executed, and the result will be the same.

Is there any way to get the date when the @Schedule task was supposed to be launched ???

+5
source share
2 answers

Is there any way to get the date when the @Schedule task was supposed to be launched ???

I think the answer is no, no.

The specification defines three interfaces that should be implemented by the container. These interfaces are: TimerService , Timer, and TimerHandle . As you can see, none of them (especially the Timer) provides the method that you need. Therefore, a Java EE compliant server is not forced to perform this behavior.

Perhaps you yourself must implement a solution that provides this requirement. For example, you can save a timestamp when the last callback method was executed and uses this timestamp to determine the time period (instead of subtracting 1 hour for the current date)

... if the server is stopped for 5 hours, the task will be started 5 times ...

Please note that you cannot rely on this.

18.4.3. Timer and timeout callback method ... Any interval constant timers or schedule-based constant timers that expired during the interim time should call the appropriate timeout callback method at least once upon reboot.

+3
source

You can restore the time during which your timer should be started using javax.ejb.Timer:

@Timeout public void timeout(Timer timer) { // get next time Date nextTime = timer.getNextTimeout(); // substract 1 hour Calendar c = Calendar.getInstance(); c.setTime(timer.getNextTimeout()); c.add(Calendar.HOUR_OF_DAY, -1); Date actualTimerDate = c.getTime(); } 
+1
source

Source: https://habr.com/ru/post/1202946/


All Articles