簡體   English   中英

從WAR自動運行線程

[英]Run a thread automatically from a WAR

我有一個包含一些jsp文件的war文件。 我在一個單獨的java文件中有一個線程,該線程會定期更新數據庫,而我的jsp文件將根據需要從數據庫中獲取數據。

現在,我需要線程從戰爭檔案自動啟動,以便它可以定期執行任務,並且用戶可以從視圖組件中獲取更新的結果。

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();
    }
}

目前出於測試目的,即時消息將分別運行此java文件,以便線程可以運行,並且我可以在JSP文件中獲取更新的結果。

有什么方法可以從WAR本身啟動線程,也可以在Web服務器啟動時自動啟動線程。 任何幫助都感激不盡。 :)

從war文件中,您可以從contextListener中執行以下操作:

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

並在web.xml中定義此偵聽器,以便在您的Web應用程序啟動時啟動,如下所示:

<listener>
    <listener-class>ContextListenerExample</listener-class>
</listener>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM