Search code examples
javaapachetomcatservletcontextlistener

how to start a function automatically on the system startup in java deployed on Apache Tomcat


I have a java web application deployed on Apache tomcat.In my application there is a function that is continuously reading the data from database.As per my need this should never be stopped.Now my concern is suppose that the system restarts ..In this case i want my that function to be called automatically without any intervention from anywhere..but i have o idea how to achieve it..

I have googled about ServletContextListener but i am not getting how to use it in my case..

Any suggestion to solve the above issue will be heartedly welcomed.. Thanks in advance..


Solution

  • Write an implementation of ServletContextListener (org.myapp.Startup.java):

    public class Startup implements ServletContextListener
    {
        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    
        @Override
        public void contextInitialized(ServletContextEvent sce)
        {
            // Do your startup work here
        }
    
    }
    

    And add it to your web.xml:

    <listener>
        <listener-class>org.myapp.Startup</listener-class>
    </listener>