0

I want to call my function on specific time interval. For now my time interval set fixed as 1 minute. I have following code example:

Timer.java

import java.util.Date;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Timer implements Runnable{
    public static volatile boolean isRunning = true;

    @Override
    public void run() {
        while (isRunning) {    
            if(Thread.currentThread().getName().equals("TimerThread")){
                System.out.println("Start Time "+new Date());

                try {
                    test();
                    Thread.sleep(60000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
                }

                System.out.println("End Time "+new Date());    
            }
        }
    }

    public void test(){
        System.out.println("Call Test ===========================> "+new Date());
    }
}

NewJFrame.java

import java.awt.event.ItemEvent;

import java.util.Date;

public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jToggleButton1 = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToggleButton1.setText("Start");
        jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jToggleButton1ItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(162, 162, 162)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(138, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(129, 129, 129)
                .addComponent(jToggleButton1)
                .addContainerGap(142, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt) {                                                
        // TODO add your handling code here:
        if(evt.getStateChange() == ItemEvent.SELECTED){
            jToggleButton1.setText("Stop");
            timer = new Timer();
            timer.isRunning = true;
            timerThread = new Thread(timer);
            timerThread.setName("TimerThread");
            timerThread.start();
        }else{
            jToggleButton1.setText("Start");
            timer.isRunning = false;
            System.out.println("Stop Time ===============> "+new Date());
        }
    }                                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    public Timer timer;
    public Thread timerThread;
    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration                   
}

When I start thread then I will get following output:

Start Time Sat Aug 08 10:45:01 IST 2015
Call Test ===========================> Sat Aug 08 10:45:01 IST 2015

Once Time interval completed then I get following output:

End Time Sat Aug 08 10:46:01 IST 2015
Start Time Sat Aug 08 10:46:01 IST 2015
Call Test ===========================> Sat Aug 08 10:46:01 IST 2015

after that I have stop my thread on 00:00:30 second so I will get following output:

Stop Time ===============> Sat Aug 08 10:46:31 IST 2015

I have stop my Thread on 00:00:30 second but my function call automatically after 00:00:30 second

Any one help me that how can I call any function on fixed time interval using Thread Just like When I click on Start button then my thread will start and call function then after wait for 2 minute. After 2 minute again call my function and repeat cycle. If I click stop button then thread will stop until I will start Thread using Start button.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
Piyush Chaudhari
  • 962
  • 3
  • 19
  • 41
  • Short answer yes, better answer, use a Swing `Timer` – MadProgrammer Aug 08 '15 at 06:21
  • What is your question exactly? What is the problem with the code you have? What did you expect to happen instead of what you saw? – JB Nizet Aug 08 '15 at 06:39
  • When I stop thread then why function call after 00:00:30 second – Piyush Chaudhari Aug 08 '15 at 06:42
  • Well, based on the output you posted, it doesn't. You stop your thread, you get the stop time in the output, and that's all. If that's incorrect, post all of your output. – JB Nizet Aug 08 '15 at 06:48
  • When I stop my thread then output as follow: Stop Time ===============> Sat Aug 08 10:46:31 IST 2015 but when stopped thread after 00:00:30 second I get following output: Start Time Sat Aug 08 10:47:01 IST 2015 Call Test ===========================> Sat Aug 08 10:47:01 IST 2015 mean thread executed automatically after 00:00:30 second – Piyush Chaudhari Aug 08 '15 at 06:57
  • I can't reproduce. Here's the complete output I get when clicking the button, waiting 1min. 30s. (approximately) and clicking it again. The thread stops, and Call Test never appears anymore in the output, as expected: https://gist.github.com/jnizet/f843b29395abcba60cf5 – JB Nizet Aug 08 '15 at 07:14
  • Why we get last line output on https://gist.github.com/jnizet/f843b29395abcba60cf5 because at second last line we already stop thread. – Piyush Chaudhari Aug 08 '15 at 07:32
  • Because you haven't actually stopped the thread. You have only set a the boolean variable `isRunning` to false, in order that, at the next iteration, when isRunning is evaluated again by the while loop, the loop stops, the run() method returns, and the thread stops running. – JB Nizet Aug 08 '15 at 07:40
  • So, how can I stop thread? – Piyush Chaudhari Aug 08 '15 at 08:52
  • You can't. Stopping a thread consists in asking it to stop, and the thread decides when to stop. That's what you did, and it worked fine. – JB Nizet Aug 08 '15 at 11:04

1 Answers1

2

The correct answer is: Don't use a Thread. Use a Timer, SwingTimer or ScheduledExecutorService depending on what you want the Thread to do.

To answer the actual question though you want then check isRunning and exit immediately after the sleep completes. You can also send an interrupt to the thread to make the sleep stop immediately if that is something you want.

Tim B
  • 40,716
  • 16
  • 83
  • 128