I would like to know if it's ok to use Timer
inside application scoped beans.
Example, lets say that I want to create a timer task that sends out a bunch of emails to every registered member one time per day. I'm trying to use as much JSF as possible and I would like to know if this is acceptable (it sounders a bit weird, I know).
Until now I have used all of the above inside a ServletContextListener
. (I don't want to use any application server or cron job and I want to keep the above things inside my web app.)
Is there a smart JSF way of doing this or should I stick with the old pattern?
As to spawning a thread from inside a JSF managed bean, it would only make sense if you want to be able to reference it in your views by #{managedBeanName}
or in other managed beans by @ManagedProperty("#{managedBeanName}")
. You should only make sure that you implement @PreDestroy
to ensure that all those threads are shut down whenever the webapp is about to shutdown, like as you would do in contextDestroyed()
method of ServletContextListener
(yes, you did?). See also Is it safe to start a new thread in a JSF managed bean?
java.util.Timer
in Java EEAs to using java.util.Timer
in a JSF managed bean, you should absolutely not use the old fashioned Timer
, but the modern ScheduledExecutorService
. The Timer
has the following major problems which makes it unsuitable for use in a long running Java EE web application (quoted from Java Concurrency in Practice):
Timer
is sensitive to changes in the system clock, ScheduledExecutorService
isn't.Timer
has only one execution thread, so long-running task can delay other tasks. ScheduledExecutorService
can be configured with any number of threads.TimerTask
kill that one thread, thus making Timer
dead, i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor
not only catches runtime exceptions, but it lets you handle them if you want. Task which threw exception will be canceled, but other tasks will continue to run.Apart from the book quotes, I can think of more disadvantages:
If you forget to explicitly cancel()
the Timer
, then it keeps running after undeployment. So after a redeploy a new thread is created, doing the same job again. Etcetera. It has become a "fire and forget" by now and you can't programmatically cancel it anymore. You'd basically need to shutdown and restart the whole server to clear out previous threads.
If the Timer
thread is not marked as daemon thread, then it will block the webapp's undeployment and server's shutdown. You'd basically need to hard kill the server. The major disadvantage is that the webapp won't be able to perform graceful cleanup via e.g. contextDestroyed()
and @PreDestroy
methods.
@Schedule
If you target Java EE 6 or newer (e.g. JBoss AS, GlassFish, TomEE, etc and thus not a barebones JSP/Servlet container such as Tomcat), then use a @Singleton
EJB with a @Schedule
method instead. This way the container will worry itself about pooling and destroying threads via ScheduledExecutorService
. All you need is then the following EJB:
@Singleton public class BackgroundJobManager { @Schedule(hour="0", minute="0", second="0", persistent=false) public void someDailyJob() { // Do your job here which should run every start of day. } @Schedule(hour="*/1", minute="0", second="0", persistent=false) public void someHourlyJob() { // Do your job here which should run every hour of day. } @Schedule(hour="*", minute="*/15", second="0", persistent=false) public void someQuarterlyJob() { // Do your job here which should run every 15 minute of hour. } }
This is if necessary available in managed beans by @EJB
:
@EJB private BackgroundJobManager backgroundJobManager;
ScheduledExecutorService
Without EJB, you'd need to manually work with ScheduledExecutorService
. The application scoped managed bean implementation would look something like this:
@ManagedBean(eager=true) @ApplicationScoped public class BackgroundJobManager { private ScheduledExecutorService scheduler; @PostConstruct public void init() { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS); } @PreDestroy public void destroy() { scheduler.shutdownNow(); } }
where the SomeDailyJob
look like this:
public class SomeDailyJob implements Runnable { @Override public void run() { // Do your job here. } }
If you don't need to reference it in the view or other managed beans at all, then better just use ServletContextListener
to keep it decoupled from JSF.
@WebListener public class BackgroundJobManager implements ServletContextListener { private ScheduledExecutorService scheduler; @Override public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS); } @Override public void contextDestroyed(ServletContextEvent event) { scheduler.shutdownNow(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With