adam bien's blog

Simplest Possible EJB 3.1 Timer - Configured Programmatically 📎

@Singleton @Startup public class PeriodicTimer { @Resource TimerService timerService; @PostConstruct public void initialize(){ ScheduleExpression expression = new ScheduleExpression(); expression.second("*/1").minute("*").hour("*"); timerService.createCalendarTimer(expression); } @Timeout public void execute(){ System.out.println("----Invoked: " + System.currentTimeMillis()); } }

 

A timer doesn't have to be a singleton - it can be a @Stateless and even a @Stateful bean. The method execute() will be invoked every second after the deployment. The programmatic registration is only an option. You could also use annotations for the timer configuration.

How to compile:

You will need the EJB 3.1 API in the classpath (few kilobytes).

How to deploy:

Just JAR or WAR the interceptor with an EJB and put the archive into e.g: [glassfishv3]\glassfish\domains\domain1\autodeploy

Btw. the initial deployment of the entire WAR took on my machine:


INFO: Loading application ProgrammaticallyCreatedTimer at /ProgrammaticallyCreatedTimer
INFO: ProgrammaticallyCreatedTimer was successfully deployed in 316 milliseconds..

How to use:

Another service can be easily injected to the timer and so invoked periodically:

@Stateless
public class HelloService {
    public String sayHello(){
        return "Hello from control: " + System.currentTimeMillis();
    }
}

And: there is no XML, strange configuration, libraries, additional dependencies needed...You will find the whole executable project (tested with Netbeans 6.8 and Glassfish v3) in: http://kenai.com/projects/javaee-patterns/ [project name: SimpleTimer].

[See also "Real World Java EE Patterns - Rethinking Best Practices"]