简体   繁体   中英

Stop and restart timer task in Android

I need to stop current running timer Task and restart it with a different delay. I tried several ways but nothing works properly. When I use the following code, TimerTask is going to run in both delays.

public void restUploadInterval(long newDelay) {
        timerRealData.cancel();
        timerRealData.purge();
        mMqttSupporter = MqttSupporter.getInstance();
        Timer timerRealData = new Timer();
        delay = newDelay;
        UploadingTask uploadingTask = new UploadingTask();
        timerRealData.scheduleAtFixedRate(uploadingTask, delay, delay);
    }

Please let me know how can I stop current timer task and run it again with a different delay.

Exactly as you did.

To restart a Timer with a different timing, you need to cancel() the old timer and create a new one.

Your code probably is not working just because you are hiding the member variable timerRealData with a local variable with the same name.

Try to change:

Timer timerRealData = new Timer();

with

timerRealData = new Timer();

and it should work.

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