Search code examples
jakarta-eeejb

JavaEE - Singleton EJB Timer doesn't work


I want to print the string "qui" every 5 seconds. I have created an EJB singleton and through annotations I defined a timeout method. I expected that the string "qui" was printed every 5 seconds , but this does not happen. The string "qui" is printed in continuation. My Application server is Glassfish. Below there is my code:

import EJBData.AuctionFrontEndLocal;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

/**
 *
 * @author melix
 */
@Startup
@Singleton
public class Timer{

    @EJB
    private AuctionFrontEndLocal auctionFrontEnd;

    private Timer timer;

    @Resource TimerService tservice;

    @PostConstruct
    public void initTimer(){
      tservice.createIntervalTimer(0,5000,new TimerConfig());
    }

    @Timeout
    public void timeout() {
      System.out.println("QUI!");
    }

}

Solution

  • your code seems ok... here is my working example:

    package com.mycompany.mavenproject2;
    
    import java.util.logging.Logger;
    import javax.annotation.PostConstruct;
    import javax.annotation.Resource;
    import javax.ejb.Singleton;
    import javax.ejb.Startup;
    import javax.ejb.Timeout;
    import javax.ejb.TimerConfig;
    import javax.ejb.TimerService;
    
    @Startup
    @Singleton
    public class NewSessionBean {
    
        @Resource
        private TimerService ts;
    
        @PostConstruct
        public void init() {
            final TimerConfig tc = new TimerConfig();
            tc.setPersistent(false);
            ts.createIntervalTimer(0, 5000, tc);
        }
    
        @Timeout
        public void timeout() {
            Logger.getLogger(NewSessionBean.class.getName()).severe("==> timeout called...");
        }
    
    }
    

    console output when i run it in glass fish 4.1

    Information:   mavenproject2 was successfully deployed in 721 milliseconds.
    Schwerwiegend:   ==> timeout called...
    Schwerwiegend:   ==> timeout called...
    Schwerwiegend:   ==> timeout called...