tags:

views:

331

answers:

3

Hi community,

I'm deploying an EJB which should set a timer and be triggered by it every 24 hours. But where should I set the timer? @PostConstruct does not help -- this is a session bean, so post-construct method will be invoked when the actual instance is created (this never happens as the sole purpose of this bean is to track timer).

Is there any other way to get notification about the bean deployment (not instantiation) in order to set up timer there?

Thanks

+3  A: 

I think that the easiest and most portable solution is to add a web-application to your enterprise-application with a context listener (contextInitialized event) that initializes the ejb.

By the way, that's more or less what the Quartz Scheduler does as well (class QuartzInitializerListener)

fvu
A: 

The solution I found is ugly, but just as ugly as any other legal solution to this problem (e.g. solution from @fvu). Applying @WebService annotation to the bean make JBoss instantiate it immediately after deployment (because it needs the way to construct the bean's WSDL), so @PostConstruct-marked method will be invoked. I was able to set a timer from there.

Sergey Mikhanov
+2  A: 

EJB 3.1 introduces the Singleton bean. It will be created at deplyoment of the EJB.

@Singleton
@Startup
public class TimerSessionBean {

    @Resource
    TimerService timerService;

    @PostConstruct
    public void startTimer() {
        Logger.getLogger(getClass().getName()).log(Level.INFO,
                timerService.getTimers().size() + " timers running");

        Logger.getLogger(getClass().getName()).log(Level.INFO, "create a timer");

        timerService.createTimer(10000, 10000, "a timer");
    }

    @Timeout
    void doSomething(Timer timer) {
        System.out.println("something");
    }
}

Another new feature in EJB 3.1 which can be used to run a task periodically is the Schedule annotation.

mjustin