How to stop scheduleTaskExecutor process?

1

Good afternoon! I'm working with Executors, I have a button that when pressing it makes a toast every 5 seconds, my question is if there is a way to kill that process by pressing the button again.

I read that with future.cancel() but I still can not implement it.

The following code is the one that shows the toast every 5 seconds

scheduleTaskExecutor = Executors.newScheduledThreadPool(0);

    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MapActivity.this, "Mensaje cada 5 segundos", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }, 0, 5, TimeUnit.SECONDS);

I hope you can help me. Thanks !!

    
asked by Ulises Díaz 05.12.2017 в 18:11
source

3 answers

2

You can stop it using the shutdown() method, as follows:

scheduleTaskExecutor.shutdown()
    
answered by 05.12.2017 / 18:19
source
1

To do so with the cancel() method of an object of type ScheduledFuture you have to obtain the object ScheduledFuture that returns the method scheduleAtFixedRate() of object scheduleTaskExecutor .

scheduleTaskExecutor = Executors.newScheduledThreadPool(0);

// Obtines el objeto de tipo ScheduledFuture que retorna el metodo scheduleAtFixedRate().
ScheduledFuture future = scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MapActivity.this, "Mensaje cada 5 segundos", Toast.LENGTH_SHORT).show();
            }
        });
    }
}, 0, 5, TimeUnit.SECONDS);

// finalizas la ejecucion de la tarea.
future.cancel(true);
    
answered by 05.12.2017 в 18:34
0

When invoking scheduledExecutor.scheduleAtFixedRate returns a ScheduledFuture . Like all implementations of Future , it has a cancel(boolean) method.

In fact this is in general for all executors; When you send them a task, it returns a Future that you can use to access the task and its results.

    
answered by 05.12.2017 в 18:27