Link to home
Create AccountLog in
Avatar of killdurst
killdurst

asked on

How to run a class that loops forever on Tomcat startup?

Hi, I would like to run a program that loops forever, in the background, when Tomcat starts. I created MyServlet.java, and in its init() method, I included the following code...

while(true){
    System.out.println("Hello world!");
    Thread t = new Thread();
    t.sleep(60000);
}

Open in new window


So basically the code will output "Hello world!" to the console every minute.

In my web.xml, I included the following tag...

<servlet>
	<servlet-name>MyServletJob</servlet-name>
	<servlet-class>com.MyServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>

Open in new window


So my Tomcat will execute MyServlet when it starts.

The problem is that I can't access the web application at all since MyServlet is still running. Since it will run continuously until the Tomcat shuts down, that means I can't access the web application at all. How do I run a program, that loops continuously, in the background, whenever Tomcat starts, and which will not affect the other servlets in my web application? Thanks!
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of killdurst
killdurst

ASKER

Thanks!