Kaltresian
Kaltresian

Reputation: 971

Starting a EJB with timer when application starts

I want to start an EJB 3.0 with timer on Weblogic 11G, but I can not use PostConstruct

What I can do to start this EJB when the application start?

@Resource TimerService timerService;

@PostConstruct
public void initialize() {


}

@Timeout
public void timeout(Timer timer)
{
    System.out.println("Timeout occurred !!!");
    if (timerService.getTimers().size() <= 1) {
        Timer newtimer = timerService.createTimer(5000,"Clean Timer");
    }

}


@Override
public void inicia() {
    if (timerService.getTimers().size() == 0) {
        Timer timer = timerService.createTimer(5000,"Clean Timer");
    }
}

Maybe in another EJB in PostConstruct I can call this?

Upvotes: 0

Views: 308

Answers (1)

marcobazzani
marcobazzani

Reputation: 463

You need to use a servlet to trigger your ejb

  1. create a servlet and override the init method

  2. Inside the init method do a JNDI lookup against your ejb and call the metod

something like this:

public class FilesystemCleanerServlet
    extends HttpServlet
{

    private static final long serialVersionUID = 3555552219242063583L;

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    public void init(ServletConfig sc) throws ServletException
    {
        super.init(sc);

        try
        {
            InitialContext ctx = new InitialContext();
            Object o =  ctx.lookup( "java:comp/env/ejb/WBFilesystemCleaner" );
        }
        catch(Exception e)
        {
            LOG.error( e.getMessage() ,e );
        }

    }   
}

or switch to ejb 3.1 if you can and do something like this:

@Startup
@Stateless
public class RunAtBootEJB {
@Schedule(second = "*", minute = "*", hour = "*", persistent = false)
public void triggerLog() {
    logging.info("printed each second");
}
} 

Upvotes: 1

Related Questions