I have implemented a timer to invoke my alert() method. The duration of the timer is retrieved from the database. When I set the duration to 1 minute, the timer invokes alert() every one minute. When I set the duration again for 5 minutes, the 1 minute timer does not stop. So now I have 2 running timers. How can I remove the previous timer? Thanks.
private void getDuration()
{
durationTimer = new javax.swing.Timer(durationDB, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
alert();
}
});
durationTimer.stop();
try
{
// Connection to the database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/smas","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM alertduration");
while (rs.next())
{
durationDB = rs.getInt("duration");
}
con.close();
}
catch(Exception ea)
{
JOptionPane.showMessageDialog(watchlist, "Please ensure Internet Connectivity ", "Error!", JOptionPane.ERROR_MESSAGE);
}
durationTimer = new javax.swing.Timer(durationDB, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
alert();
}
});
durationTimer.start();
Call the stop() method when you are finished with the first timer. It may also be worth making your timer global and reusing it rather than creating a new one every time the duration changes. See: http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html
Example: