Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel timerTask for AsyncTask in android

Hi I am working on TCP socket. I can read data for every 1 sec. to achieve it I used TimerTask as shown in below code.

Handler handler = new Handler();
Timer timer = new Timer();

TimerTask doAsynchronousTask = new TimerTask() {

        @Override
        public void run() {
            finalizer = new Runnable() {
                public void run() {
                    try {
                        if (navBool) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    new RetriveStock().execute(); // AsyncTask.
                                }
                            });

                        }
                    } catch (Exception e) {
                    }
                }
            };
            handler.post(finalizer);
        }
    }; 
timer.schedule(doAsynchronousTask, 0, 1000);

For canceling this timer I used code as

timer.cancel();
timer = null;
handler.removeCallbacks(finalizer);

But it is not cancelling the timer. I do not know why.

like image 832
user2085965 Avatar asked Dec 03 '25 11:12

user2085965


1 Answers

Instead of calling timer.cancel(), you should be canceling the task that is assigned to that timer (doAsynchronousTask in your case). Since multiple TimerTasks can be assigned to one timer, calling timer.cancel() will not interfere with a currently running task.

From the Timer JavaDoc:

public void cancel()

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

like image 63
Ben Siver Avatar answered Dec 05 '25 00:12

Ben Siver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!