0

I used this code to start a listener before Tomcat initializes, but it has a while loop in it that will check a database every 5 seconds for changes. Is there any way that I can skip the looping part of that until my web service has been started completely, then trigger the loop to begin checking?

EDIT: Meant listener and not Servlet

EDIT2: Code below

public class DatabaseChecker implements ServletContextListener {

final static String URL = "redacted";
final static String USER = "redacted";
final static String PASS = "redacted";

@Override
public void contextInitialized(ServletContextEvent event) {

    Vector<String> completedJobs = new Vector<String>();

    try {
        while(true) {   // loop to always check & notify
            Thread.sleep(5000);
            System.out.println("Checker running ...");
            // completedJobs = selectCompletedJobs();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("ServletContextListener destroyed");

}

}

xtheking
  • 531
  • 2
  • 7
  • 23
  • 3
    That's just wrong. The while loop is going to prevent the context listener from ever finishing, and thus your application will probably remain in a not-initialized state. The sleeping-busy while loop should probably be happening in a separate background thread. Like so: http://stackoverflow.com/questions/4691132/how-to-run-a-background-task-in-a-servlet-application – Gimby Oct 01 '15 at 16:15
  • @Gimby that worked!!! Wanna make that an answer so I can give you that checkmark? ;) – xtheking Oct 01 '15 at 16:35
  • the fact that another question+answer entirely answers yours makes your question a duplicate. Hence BalusC correctly did the paperwork. – Gimby Oct 02 '15 at 07:36

1 Answers1

0

Yes. The ServletContext allows you to add attributes, which is a global context shared between the ServletContextListener and the services running in the servlet.

You can have the ServletContextListener wait for the web service by polling for an attribute.

When your web service is ready, it can add the attribute to the ServletContext.

Now when your ServletContextListener finds the attribute, it can proceed.

sh0rug0ru
  • 1,496
  • 7
  • 8