How to implements java timer in server side?

Hello I am currently working on a middleware application

Im using JSF and primefaces and the deployment is in tomcat server ,
I was able to develop a notification system using JAVA.mail and i am using java timer to schedule the notification every 24H

For the moment it works fine when I run my main class but when i run the whole project the process of javaTimer doesn’t work and i have no idea how to make run in server side without launching the class Main

So i ask if should add something to make it run when i launch my project

Here my code :

public class Job1 {
    public static void main(String[] args) throws Exception {
        // execute method review_date() every 1 minute
        risk r = new risk();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                try {
                    r.review_date2();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000 * 60);
    }
}

>Solution :

If I need app-wide resources, I usually implement the ServletContextListener, then specify it to be run in web.xml. However, swing timers likely don’t work so you’ll need a ScheduledExecutorService instead.

package mypackage;

import javax.servlet.*;

public class MainContextListener implements ServletContextListener {

    ScheduledExecutorService service;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        service = newSingleThreadScheduledExecutor();
        risk r = new risk();
        service.scheduleAtFixedRate(() -> {
            try {
                r.review_date2();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, 1, TimeUnit.DAYS);
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        service.shutdown();
    }
}
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
 id="WebApp_ID" 
version="4.0">
  <!-- etc. -->
  <listener>
    <listener-class>mypackage.MainContextListener</listener-class>
  </listener>
</web-app>

Leave a Reply