How to remove previous Timer in java? - java

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:
durationTimer = new javax.swing.Timer(duration, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
alert();
}
});
durationTimer.start();
//wait for duration to change
durationTimer.stop();
durationTimer.setDelay(duration);
durationTimer.start();

Related

How to kill/stop task/timer with manual given time

My code
setSelectedTime(duration){
duration = 5 //this duration can be dynamic. User can select the time in minutes
timer = new Timer();
TimerTask task = new TimerTask() {
public void run(){
try {
performing task Here....
} catch(Exception e) {
log.error("Exception"+e);
}
}
};
timer.schedule(task, duration*60*1000);
}
How to kill the existing timer/task when user change the input.

Java swing countdown timer not working properly

I would like to make a program that shuts down the computer after specific time, but I have troubles making the timer countdown. It must decrement the time in the spinners from which it takes it. I tried to make a dynamic dialog application but it doesn't work.
I apply the whole code if that is not enough.
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//decrements the amount of seconds and the time in the spinners
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
hours.setValue((Integer)m_hours);
minutes.setValue((Integer)m_mins);
seconds.setValue((Integer)m_secs);
label_2.setText(ShutDownDialog.
this.AmountOfTime.toString());
}
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop"); //just to check what happens
}
}
});
StartCountdown.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
hours.setEnabled(false);
minutes.setEnabled(false);
seconds.setEnabled(false);
StartCountdown.setEnabled(false);
StopCount.setEnabled(true);
//calculates the amount of seconds and starts the timer
m_hours = ((Integer)hours.getValue()*3600); //get the hours
m_mins = ((Integer)minutes.getValue()*60); //get the minutes
m_secs = (Integer)seconds.getValue(); //get seconds
AmountOfTime = m_hours + m_mins + m_secs;
timer.start();
//JOptionPane.showMessageDialog(null, AmountOfTime);
}
});
You are updating the values only, if m_secs < 0.
Move
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
outside of the if-block and it will update the labels.
It should now look like this:
private void initialize() {
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
}
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
label_2.setText(ShutDownDialog.this.AmountOfTime.toString());
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop");
}
}
});

Do Java Swing action on specified Date

I'm trying to create a program which has two options:
- Do specific task after countdown (in minutes).
- Do specific task on the date selected.
Both are using jSpinners however, I don't know how to do the action on the specific date, here's the code below, thank you in advance!
protected Object doInBackground() throws Exception {
Timer t = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Checking state of CheckBoxes (one cancels the other)
if(jCheckBox2.isSelected()) {
try {
int delay =(int) jSpinner2.getValue();
jCheckBox1.setSelected(false);
Thread.sleep(delay*60000); //To delay the code from miliseconds to minutes
} catch (InterruptedException ex) {
Logger.getLogger(App_Gui.class.getName()).log(Level.SEVERE, null,
ex);
}
}
else if (jCheckBox1.isSelected()) {
Date delay2 = (Date) jSpinner1.getValue();
jCheckBox2.setSelected(false);
Thread.sleep(delay2); //What should I put here instead of Thread.sleep()???????
}
//If all is right, start the timer
t.start();
t.setRepeats(false);
//Popup dialog
JDialog dialog = new JDialog();
dialog.setLocation(700, 300);
dialog.setSize(600, 400);
dialog.setVisible(true);
//Speed of color changing
try {
Thread.sleep(jSlider1.getValue());
} catch (InterruptedException ex) {
Logger.getLogger(App_Gui.class.getName()).log(Level.SEVERE, null,
ex);
} //Setting the color
dialog.getContentPane().setBackground(jLabel2.getBackground());
dialog.setModal(true);
Assignment_Tajmer_Aplikacija.f.setVisible(false);
return null;
}
protected void done() {
System.out.println("Done!");
}
};
sw.execute();
}
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling cosadde here:
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
//System.out.println(source.getValue());
}
});
}
You have 2 choices:
You compute time difference in milliseconds between current date and target date. So you can start the swing timer. Something like myDate.getTime() - Sytem.currentTimeMillis() (it's probably not always correct)
You use a Library which do it for you (for example Quartz). In this case you need to synchronize your job with the Swing thread using the method SwingUtilities.invokeLater(Runnable).
And never use Thread.sleep() in a Swing application. Start a timer instead.

How to stop a timer

I have the following action performed method
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer();
Object source = e.getSource();
String stringfromDate = tffromDate.getText();
String stringtoDate = tftoDate.getText();
if (source == button) {
// auto refresh begins
int delay = 0; // 0 seconds startup delay
int period = 7000; // x seconds between refreshes
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
// i still have to truly understand what overide does however
// netbeans prompted me to put this
public void run() {
try {
getdata(stringfromDate, stringtoDate);// run get data
// method
} catch (IOException | BadLocationException ex) {
Logger.getLogger(JavaApplication63.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}, delay, period);
}
if (source == button1) {
timer.cancel();
textarea.setText("");
}
}
I have 2 buttons on my GUI one called get information(button) and another called clear information (button1).
I cant seem to get my clear information(button1) to stop the timer and clear the text area so that a new search can be performed. I just cant seem to get this to stop help appreciated.
Consider these changes to your code. Mainly the code does these things differently:
Pull up the declaration of your timer into the class, so that the same timer started before can be cancelled later.
only create a new timer if the start-button was pressed.
//Pulled up for access to make canceable .
protected Timer timer;
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String stringfromDate = tffromDate.getText();
String stringtoDate = tftoDate.getText();
if (source == button) {
//Stop existing one before creating new.
if(timer != null) {
timer.cancel();
}
//Now make new
timer = new Timer();
// auto refresh begins
int delay = 0; // 0 seconds startup delay
int period = 7000; // x seconds between refreshes
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
getdata(stringfromDate, stringtoDate);// run get data
// method
} catch (IOException | BadLocationException ex) {
Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex);
}
}
}, delay, period);
}
if (source == button1) {
//NULLCHECK
if(timer != null) {
timer.cancel();
}
textarea.setText("");
}
}

Pass SQL Connection to ActionListener (Thread)

How can I pass a SQL connection to a Action Listener. I want to have an infinite loop, that sleeps for 100ms. Every iteration the loop is suppose to query a database. Is swing timer the best way to do this? If so how can I pass the connection to the Action Listener. If not, can someone please advise on how this can be done. Much thanks.
Code:
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
AdminManager frame = new AdminManager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
BoneCP connectionPool = null;
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://192.162.0.0");
config.setUsername("root");
config.setPassword("");
connectionPool = new BoneCP(config); // setup the connection pool
connection = connectionPool.getConnection(); // fetch a connection
if (connection != null){
System.out.println("Connection successful!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Define listner
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
String sql = "SELECT * table;";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
String symbol = rs.getString("name");
System.out.println(symbol);
}
}
};
Timer timer = new Timer( 100 , taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(1000);
//connectionPool.shutdown(); // shutdown connection pool.
}
Do not the javax.swing.Timer class to periodically execute a non-Swing task. Instead, use a ScheduleExecutorService,
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
#Override
public void run(){
// query database
}
}, 0, 100, TimeUnit.MILLISECONDS);
If the background task must continually update a Swing component, use SwingWorker to process() periodic updates to the component's model. In this example, a JTextArea is updated with data obtained from an H2 database.

Categories