Java.util.timer定时器空指针异常



我使用Apache Tomcate 7.0.39, Eclipse Java EE Juno, Java JRE 7 &Java JDK 1.7.0_13.

我的计时器有问题。我有两个函数,第一个启动计时器并执行任务,另一个停止计时器。但是计时器永远不会停止,因为它是空的。

My Java code:

public class TestXMLSQLTimerLocal
{
    public Timer timer;
    public TestXMLSQLTimerLocal()
    {
    }
    public void start()
    {
        this.timer = new Timer();
        TimerTask task = new TimerTask()
        {
            public void run()
            {
            //Some code
            }
        };
        timer.scheduleAtFixedRate(task, 0, 60000);
    }
    public void stop() {
        this.timer.cancel();
    }
}

我的JSP页面:

<%@page import="com.accenture.api.TestXMLSQLTimerLocal" %>
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%
String text = "Press the Start button to begin !";
String action = request.getParameter("action");
TestXMLSQLTimerLocal TM = new TestXMLSQLTimerLocal();
if ("Start".equals(action))
{
    TM.start();
    text = "The data are being transferred. Press the Stop button when you want to stop the transfer !";
}
if("Stop".equals(action))
{
    TM.stop();
    text = "The transfer is stopped. Press the Start button to begin the transfer again !";
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Transfer Module</title>
</head>
<body>
    <form name="StartTM" action="#">
        <input type="hidden" name="action" value="Start"/>
        <input type="submit" value="Start"/>
    </form>
    <br />
    <p><%=text%></p>
    <br />
    <form name="StopTM" action="#">
        <input type="hidden" name="action" value="Stop"/>
        <input type="submit" value="Stop"/>
    </form>
</body>
</html>

start()和stop()由简单JSP页面上的start和stop按钮调用。

对我来说,问题是定时器仍然是空的,因为Start()方法中的修改没有考虑在内。有人能帮我吗?如果您需要更多的信息,请问我

在构造函数中初始化计时器,而不是在start方法中:

public class TestXMLSQLTimerLocal
{
public Timer timer;    
public TestXMLSQLTimerLocal(){
   this.timer = new Timer();
}
public void start()
{
    TimerTask task = new TimerTask()
    {
        public void run()
        {
        //Some code
        }
    };
    timer.scheduleAtFixedRate(task, 0, 60000);
}
public void stop() {
    this.timer.cancel();
}
}

您需要确保启动命令在停止命令之前被调用。此外,将this.timer = new Timer();放入类的构造函数中。

如果从JSP调用,则当用户按下停止按钮时,生成新线程的TestXMLSQLTimerLocal实例以及Timer都不可用。

您需要在会话中添加TestXMLSQLTimerLocal的实例,或者更理想的是添加applicationContext。当你对这个实例执行操作时,总是把它从会话中拉出来。

添加TestXMLSQLTimerLocal实例到会话:

//From Servlet
request.getSession().addAttribute("timer", new TestXMLSQLTimerLocal());

要将实例添加到应用程序范围中,您需要使用ServletContextListener

由于从未创建Timer的实例,因此代码将抛出NPE错误。

我找到了解决方案,感谢Kevin Bowersok

我将开始和停止按钮分成两个页面,并通过会话发送我的TestXMLSQLTimerLocal对象。

通过会话发送对象:

session.putValue("TM",TM);

获取另一页中的值:

TestXMLSQLTimerLocal TM = (TestXMLSQLTimerLocal) session.getValue("TM");

谢谢大家的帮助

最新更新