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.


Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Is injection available in invokePeriodically()?

Posted by Hwq on September 10, 2017 at 01:41 PM CEST #

Thats an easy way of doing it, even though I guess you cannot guarantee the portability when it comes to @RequestScoped beans or? The spec says its not recommended (compared to EJB Timers where it work). Ofcourse it all depends on if you need it...

Another view on it is that you are still using EJBs (@Startup @Singleton).... maybe it can be replaced by observing @Initialized(ApplicationScoped)... (or by setting it up in a method observing AfterDeploymentValidation in an extension).

Love your posts, keep it up!

Posted by LF on September 10, 2017 at 08:07 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License