Using persistent and non-persistent timers

Timers can be either persistent or non-persistent. In this recipe, we will learn more about what persistence means and how to create either a persistent or non-persistent timer.

Getting ready

A persistent/non-persistent timer is created using the @Schedule annotation and setting its persistent attribute to true/false. If programmatic timers are being used, the TimerConfig's setPersistent method is passed an argument of true/false.

Persistent timers are able to survive application and server crashes. When the system recovers, any persistent timers will be recreated and missed callback events will be executed. When replay of missed timer events is not desired, then a non-persistent timer should be used. For example, we probably do not want to send out meeting notices for a meeting which has already been held.

A persistent timer survives when:

  • The container crashes
  • The server shuts down
  • From activation/passivation

How to do it...

By default, timers are persistent. A non-persistent timer is created using the @Schedule annotation and setting its persistent attribute to false.

@Schedule(second="0", minute="*", hour = "*", info="", persistent=false)

Programmatic calendar-based timers can be created using the createCalendarTimer method. The second argument of this overloaded method is a TimerConfig argument. By passing false to its setPersistent method we can create a non-persistent timer.

TimerConfig timerConfig = new TimerConfig();
timerConfig.setPersistent(false);
...
timerService.createCalendarTimer(scheduleExpression,timerConfig);

How it works...

Timers are persistent by default. However, by setting the persistent attribute to false or using the setPersistent method with a false argument we saw how they can be made non-persistent. You may want to stop and then restart to server to verify how these settings work.

There's more...

There is only one instance of a persistent timer per application regardless of the number of JVMs the application is deployed to. Non-persistent timers are created within their JVM.

From a callback method, the Timer's isPersistent method can be used to determine whether the timer is persistent or not. This method is illustrated in the Using the timer interface recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.59.219