简体   繁体   中英

Can not stop TimerTask

I have a problem with my Java code when doing with Wii Remote. My situation is "When button A presses, print something to the screen (the raw acceleration in my case) until releasing button A", so, after few days of searching, i use TimerTask and Timer for doing task. It printed the raw acceleration. Howerver, after i release button A, it cannot stop printing. Here is my code:

public class TestTimerTask implements WiimoteListener { 
    public RawAcceleration rawacc;    
    public static void main(String[] args){        
        Wiimote[] wiimotes = WiiUseApiManager.getWiimotes(1, true);
        Wiimote wiimote = wiimotes[0];
        wiimote.activateMotionSensing();
        wiimote.toString();
        wiimote.addWiiMoteEventListeners(new TestTimerTask ());  
    }
    @Override
    public void onButtonsEvent(WiimoteButtonsEvent wbe) {

        boolean check = false;
        Timer timer = new Timer();
        TaskNeedToDo task = new TaskNeedToDo();

        if(wbe.isButtonAJustReleased()){

            System.out.println("Button A Just Released");
            task.setCheck(false);
            task.cancel();
            timer.cancel();
        }

        if(wbe.isButtonAJustPressed()){
           // check = false;
            try {
                System.out.println("Button A Just Pressed");       
                DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss");
                Date temp = new Date (System.currentTimeMillis());


                Date now = dateFormatter.parse(dateFormatter.format(temp));


                int period = 300;
                task.setCheck(true);
                task.setRawAcc(rawacc);
                timer.schedule(task, 0, period);


            } catch (ParseException ex) {
               System.out.println("Error when take current time");
            }           

        }        

        if(wbe.isButtonBHeld())
            WiiUseApiManager.shutdown();
    }

    @Override
    public void onIrEvent(IREvent ire) {
         System.out.println("onIrEvent oocur");
    }

    @Override
    public void onMotionSensingEvent(MotionSensingEvent mse) {
        rawacc = mse.getRawAcceleration();
    }
     class TaskNeedToDo extends TimerTask {
    private boolean check;
    private RawAcceleration value;

    public boolean getCheck(){
        return check;
    }
    public void setCheck(boolean check){
        this.check = check;
        if(check == false)
            this.cancel();
    }
    public RawAcceleration getRawAcc(){
        return value;
    }
    public void setRawAcc(RawAcceleration value){
        this.value = value;
    }
    @Override
    public void run() {
        if(check == false)
            this.cancel();        

        System.out.println(value);
        System.out.println(check);
    }
}

And here is the result:

Button A Just Pressed

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148)

true

Button A Just Released

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148)

true

Raw acceleration : (14, 115,148

true

The check stills true, so it cannot stop :( Thanks for helping me :D

When you are calling timer.cancel() you are calling it on a new instance of timer. So you are not cancelling the timer that you had previously scheduled.

I would suggest storing the timer as a class level field. Make sure it is only instantiated once (with new Timer() ) and then ensure that when you call cancel it is the same instance that you called schedule on.

Uber simplified version:

public class TestTimerTask implements WiimoteListener { 

    private Timer timer = new Timer();

    @Override
    public void onButtonsEvent(WiimoteButtonsEvent wbe) {

        if(wbe.isButtonAJustReleased()) {
            timer.cancel();
        }

        if(wbe.isButtonAJustPressed()) {
            timer.schedule(...);
        }

    }

}

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