简体   繁体   中英

Stop a timer with a button

I have a start button that starts a timer with a loop.

public synchronized void startTourButtonActionPerformed(java.awt.event.ActionEvent evt) {
    new java.util.Timer().schedule(new java.util.TimerTask() {
        @Override
        public void run() {

            try {
                byte st = presetNo[count];
                System.out.println("Start Tour Button pressed, String:  " + st);

                // this part will run from 0 to max of presets every
                // counting.
                count++;
                if (count >= MaxCount)
                    count = 0;

                byte[] command = { (byte) startTx, address, byteOne, goPreset, 0x00, st, endTx, 0x0F };
                TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
                        twoWaySerCom.serialPort.getOutputStream());

                sw.out.write(command);

            }

            catch (IOException e) {
                e.printStackTrace();
            }

        }
    }, 100, 5000);
}

And I have another 'Stop' Button. Currently i am stopping the loop by breaking it and getting an Exception. Obviously not the correct procedure and also stops the start button from working.

public synchronized void stopTourButtonActionPerformed(java.awt.event.ActionEvent evt){
    count = -1;
}

My question is how do i stop it correctly so that i can restart afterwards?

Just keep a reference of the timer (a variable) and call the cancel() method.

In startTourButtonActionPerformed

//...
timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
//...

In stopTourButtonActionPerformed

timer.cancel();

Note the it will cancel all your timer 's tasks. There is also a cancel() method on a TimerTask if you want to precisely stop only one single task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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