2014-12-28 4 views
1

임. 일부 jsp 파일이 포함 된 war 파일이 있습니다. 데이터베이스를 주기적으로 업데이트하고 jsp 파일이 필요할 때 데이터베이스에서 데이터를 가져 오는 개별 Java 파일에 스레드가 있습니다.WAR에서 스레드를 자동으로 실행합니다.

이제 태스크를 주기적으로 수행하고 사용자가보기 구성 요소에서 업데이트 된 결과를 얻을 수 있도록 스레드를 war 아카이브에서 자동으로 시작해야합니다.

public class AttendanceThread { 
    private long DEFAULT_SLEEP_TIME = 10000;// 10 seconds. 
    private long MAX_SLEEP_TIME = 30000;// 30 seconds. 
    private int shift; 

    public void MonitorAtttendance() { 
     final UpdateAttendance updateObject = new UpdateAttendance(); 
     Runnable attThread = new Runnable() { 
      @Override 
      public void run() { 
       try { 
          // logic to calculate the current shift time 

          updateObject.CheckEmpAttendance(shift); 
          updateObject.resetUpdatedAttendance(shift); 
          Thread.sleep(MAX_SLEEP_TIME); 
         } else { 
          Thread.sleep(DEFAULT_SLEEP_TIME); 
         } 
        }// end of while (true) 
       } catch (Exception e) { 
             } 
      }// end of run() 
     }; // end of attThread definition 
     Thread t = new Thread(attThread); 
     t.setName(this.getClass().getSimpleName()); 
     t.start(); 
    } 

    public static void main(String args[]) { 
     // logger.log(Level.INFO, "Monitor Atttendance"); 
     AttendanceThread ma = new AttendanceThread(); 
     ma.MonitorAtttendance(); 
    } 
} 

현재 테스트를 위해이 자바 파일을 separetely로 실행하여 스레드를 실행할 수 있고 JSP 파일에서 업데이트 된 결과를 얻을 수 있습니다.

웹 서버가 시작될 때 WAR 자체에서 또는 자동으로 스레드를 시작할 수있는 방법이 있습니까? 어떤 도움을 많이 주시면 감사하겠습니다. 웹 응용 프로그램은 다음과 같이 시작하면

public class ContextListenerExample implements ServletContextListener { 
    public void contextInitialized(ServletContextEvent e){ 
     ServletContextcntxt = e.getServletContext(); 
     //start your thread here 

그리고 당신의 web.xml이 리스너를 정의하는, 그래서 시작 : : : 당신의 전쟁 파일에서

+0

빈으로 연결해야합니다. –

답변

2

, 당신은 같은 contextListener에서 동일한 작업을 수행 할 수

<listener> 
    <listener-class>ContextListenerExample</listener-class> 
</listener> 
+0

이 작업을 처리하기 위해 별도의 서블릿이 필요합니까? 참고로, 저는 서블릿을 사용하고 있지 않습니다. 프로토 타입은 jsp 자체에서 db 값을 얻고 있습니다. – vembutech

+0

아니요.이 경우 서블릿이 필요하지 않습니다. 위와 같이 리스너 클래스를 정의하고 스레드를 시작하면된다. 리스너의 contextInitialized 메소드는 웹 응용 프로그램의 진입 점입니다. – SMA

+0

그래서 ServletContextListener를 구현하여 내 스레드 클래스를 작성해야하며 모든 스레드 코드는 contextInitialized() 메소드로 이동합니다. – vembutech

관련 문제