简体   繁体   English

从WAR自动运行线程

[英]Run a thread automatically from a WAR

Im having a war file which contains some jsp files. 我有一个包含一些jsp文件的war文件。 I have a thread in a separate java file which updates the database periodically and my jsp files will get data from the database on demand. 我在一个单独的java文件中有一个线程,该线程会定期更新数据库,而我的jsp文件将根据需要从数据库中获取数据。

Now , I need the thread to start automatically from a war archive so that it can do the tasks periodically and the user can get updated results from the view component. 现在,我需要线程从战争档案自动启动,以便它可以定期执行任务,并且用户可以从视图组件中获取更新的结果。

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

Currently for test purposes, im running this java file separetely so that the thread can run and i can get updated results in my JSP files. 目前出于测试目的,即时消息将分别运行此java文件,以便线程可以运行,并且我可以在JSP文件中获取更新的结果。

Is there any way we can start the thread from the WAR itself or automatically when the web server starts. 有什么方法可以从WAR本身启动线程,也可以在Web服务器启动时自动启动线程。 Any help will be much appreciated. 任何帮助都感激不尽。 :) :)

From your war file, you could do the same from contextListener like: 从war文件中,您可以从contextListener中执行以下操作:

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

And define this listener in your web.xml, so it starts when your web application starts as below: 并在web.xml中定义此侦听器,以便在您的Web应用程序启动时启动,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM