繁体   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