March 28, 2016

Scheduling/Time Service in Java EE 6

In Java EE 6 is scheduling feature already built in.

Example from The Java EE 6 Tutorial (http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html).

Also good reading from Arun Gupta - https://blogs.oracle.com/arungupta/entry/totd_146_understanding_the_ejb

After reading the above I came across the following pitfalls.

Do not use persistent scheduling, because this means if you stop your server and then restart it. All scheduling event that should have taken place during shutdown will now run. Like a catchup effect.

  • Annotation way: javax.ejb.Schedule.persistent()
  • Programmatic way: javax.ejb.TimerConfig.TimerConfig(Serializable, boolean)

Another side effect is the default transaction type of javax.ejb.TransactionAttributeType.REQUIRED for all EJB. This is not always not wanted, because the meaning of a failed scheduling is it will be rerun.

I suggest changing default transaction type not supported and then move all logic to another EJB which will start transaction.

// Singleton Session Bean
@javax.ejb.Singleton
// "If the transaction is rolled back, the container will call the @Timeout
// method at least one more time." [Oracle Java EE 6 Tutorial]
@javax.ejb.TransactionAttribute(javax.ejb.TransactionAttributeType.NOT_SUPPORTED)
public class MyTimerBean {
...
}

And if you want your scheduling to start at boot use @javax.ejb.Startup

// Start at boot
@javax.ejb.Startup
// Singleton Session Bean
@javax.ejb.Singleton
// "If the transaction is rolled back, the container will call the @Timeout
// method at least one more time." [Oracle Java EE 6 Tutorial]
@javax.ejb.TransactionAttribute(javax.ejb.TransactionAttributeType.NOT_SUPPORTED)
public class MyTimerBean {
...
}

No comments: