since you clarified the question, here is another answer: how to start the daemon in tomcat:
first register your daemons in web.xml:
<listener> my.package.servlet.Daemons </ listener>
then implement the Daemons class as an implementation of ServletContextListener as follows:
the code will be called every 5 seconds, tomcat will call contextDestroyed when your application shuts down. note that the variable is volatile, otherwise problems may occur when turning off multi-core systems.
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Daemons implements ServletContextListener { private volatile boolean active = true; Runnable myDeamon = new Runnable() { public void run() { while (active) { try { System.out.println("checking changed files..."); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; public void contextInitialized(ServletContextEvent servletContextEvent) { new Thread(myDeamon).start(); } public void contextDestroyed(ServletContextEvent servletContextEvent) { active = false; } }
source share