adam bien's blog

A Java EE 7+ Alternative To EJB Timers 📎

In addition to EJB timers (Simplest Possible EJB 3.1 Timer), with Java EE 7+ you can directly inject ManagedScheduledExecutorService, a subclass of ScheduledExecutorService available in stock Java SE:

    
        import java.time.LocalTime;
        import java.util.concurrent.TimeUnit;
        import javax.annotation.PostConstruct;
        import javax.annotation.Resource;
        import javax.ejb.Singleton;
        import javax.ejb.Startup;
        import javax.enterprise.concurrent.ManagedScheduledExecutorService;
        
        @Startup
        @Singleton
        public class Scheduler {
        
            static final long INITIAL_DELAY = 0;
            static final long PERIOD = 2;
        
            @Resource
            ManagedScheduledExecutorService scheduler;
        
            @PostConstruct
            public void init() {
                this.scheduler.scheduleAtFixedRate(this::invokePeriodically, 
                        INITIAL_DELAY, PERIOD, 
                        TimeUnit.SECONDS);
            }
        
            public void invokePeriodically() {
                System.out.println("Don't use sout in prod " + LocalTime.now());
            }
        
        }
    
Immediately after deployment, you should find the following output (likely with different timestamp :-):
    
        Info:   Don't use sout in prod 11:31:39.093
        Info:   Don't use sout in prod 11:31:41.097
        Info:   Don't use sout in prod 11:31:43.096
    
(ManagedScheduledExecutorService replaced EJB 3.1 timers in a project as a workaround to appserver configuration issues in production) See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.