Filipe Gonçalves Filipe Gonçalves - 2 months ago 11
Android Question

Stop a TimerTask without stopping the Timer

I have a

Timer
and I schedule a task for it at a certain fixed rate, using the method
scheduleAtFixedRate
. The problem is that after some actions, i want to finish/cancel this task that was scheduled before.

I know that i can use
.cancel()
or
.purge()
but that will cancel/finish my timer, which is something that i don't want to. I just want to finish the task.

Does any of you know how to do this ?

This is my code (I have the
Timer
created as a field of the class)

receiveTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {

int fileSize=(int)fileSizeToReceive;
int actual= totalReceived;

((Notification.Builder) mBuilderReceive).setContentText("Receiving "+actualNameToReceive);
((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false);
mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification());
}
},0,500);//delay, interval

Answer

Just hold a reference to your TimerTask so you can call cancel() on it whenever you'd like.

Calling cancel() on the TimerTask will not stop the Timer.

For example, declare your task:

TimerTask task;

Initialize and schedule it:

task = new TimerTask() {
    @Override
    public void run() {
        int fileSize=(int)fileSizeToReceive;
        int actual= totalReceived;

        ((Notification.Builder) mBuilderReceive)
            .setContentText("Receiving  "+actualNameToReceive);
        ((Notification.Builder) mBuilderReceiver)
            .setProgress(fileSize, actual, false);
        mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive)
            .getNotification());
    }
};

receiveTimer.scheduleAtFixedRate(task, 0, 500);

To stop it, you just have to call cancel() on the task instance:

task.cancel();