Showing posts with label Timer. Show all posts
Showing posts with label Timer. Show all posts

13.2.12

EJB 3.1 Timer Service: Like a Boss

The EJB 3.1 specification introduces new additional cron-style timer service. It is now possible to define automatically created and cronjob like EJBs.

Our first simple example takes advantage of the newly introduced annotation:

@Singleton
public class MyTimer {
    @Schedule(minute="*", second="*/3", hour="*" ,persistent=false)
    public void timing(){
        System.out.println("yeah, i'm an automatic timer service");
    }
}

The @Schedule annotation allows you to define the timing behaviour of your service in details (year, month, day .... timezone). It is also possible to create combinations:

    @Schedules({
        @Schedule(minute="*", 
                  second="*/10", 
                  hour="*" ,persistent=false),
        @Schedule(minute="*", 
                  second="*/5", 
                  hour="*" ,persistent=false)
    })
    public void detailTiming(){
        System.out.println("very detailed timer service");
    }

If you want to set your timing behavior dynamically on runtime, you use a combination of the old 3.0 annotations and the newly introduced class ScheduleExpression.


@Singleton
@Startup
public class ProgramaticalTimer {

    @Resource
    private TimerService timerService;
   
    @PostConstruct
    public void init(){
        ScheduleExpression expression = new ScheduleExpression();
        expression.second("*").minute("*").hour("*");
        timerService.createCalendarTimer(expression);
    }
    @Timeout
    public void timeIt(){
        System.out.println("A bit old school.");
    }
}
As you already noticed the @Startup annotation was added; only timers marked with @Schedule are created automatically. This workaround provides the wanted behaviour in a different way.
Furthermore, according to the EJB 3.1 spec:
For automatically created timers, the timeout method may be a method that is annotated with the Schedule annotation. Timers can be created for stateless session beans, singleton session beans, message-driven beans, and 2.1 entity beans[94]. Timers cannot be created for stateful session beans[95] ... The timer service is intended for the modelling of long-lived business processes. Timers survive container crashes, server shutdown, and the activation/passivation and load/store cycles of the enterprise beans that are registered with them. These persistent guarantees can optionally be disabled on a per-timer basis.
Following values are valid for schedule properties:
  • Single Value (10)
  • Wild Card (*) 
  • List (Mon, Wed, Fri) 
  • Range(Fri-Mon) 
  • Increments(30/10)
For more detailed information take a look into the EJB 3.1 spec

12.12.11

Simple EJB 3.0 Timer

Creating an EJB 3.0 Timer is pretty straight forward.
First, the TimerService is needed. It can be  retrieved direclty via Dependency Injection or using the SessionContext.

@Resource
private javax.ejb.TimerService timerSerivce;

The TimerService interface offers different methods for the creating the actual timer. Most important is the differentiation between  single-event and interval.

public void doSmg() {
     System.out.println("Create Timer");
     timerSerivce.createTimer(3000,3000,  
                            "ObjectAccessibleInTheTimeoutMethod");
}

The first parameter indicates when the timer goes off; the value must be relative, so in this case it will be executed in 3 seconds. For details on the method signatures, please refer to the API doc.
Within the same Bean a method with the following signature and annotation is needed:

@Timeout
 public void timeSomething(Timer timer) {
        System.out.println(timer.getInfo());
 }

It is executed whenever the timer goes off. The getInfo() method returns the passed serializable Object, in this case the String "ObjectAccessibleInTheTimeoutMethod".

Timer Facts:
  • Timers are persistent by specification, if the server crashes or is shutdown, created timers must still exist. However, just to get sure check your server's documentation, e.g. older JBoss servers versions delete timers after  a shutdown. Furthermore, the persisting - implementation is not specified, so this can vary too.
  • If the execution of a timer was missed, because e.g. the server was shut down, it will immediately be called after the server is back online.
  • The timer methods (annotated with @Timeout) are execeuted within a transaction.
  • Possible just for Message Driven and Stateless Session Beans