+1  A: 

You need to call scheduleFuture.shutdown() to stop the execution. Otherwise it is restarted every seond.

Develman
Should call scheduledExecutorService.shutdown() instead of scheduleFuture.shutdown(), and ScheduledExecutorService.schedule() call is one-shot action, that will never be restarted again.
moonese
+2  A: 

ScheduledExecutorService is used to schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. unless ScheduledExecutorService is shutdown tasks run periodically.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

daedlus
eh, schedule() won't run tasks periodically (see API) it'll just execute once with the specified delay.
Enno Shioji
not the method schedule() what i meant was it has diferent schedule methods.ex:-scheduleAtFixedRate
daedlus
+1  A: 

A scheduled task is either being executed or is waiting to be executed.

If the task is waiting to be executed, future.cancel() will prevent it from being executed (both cancel(true)/cancel(false)).

If the task is already being executed, future.cancel(false) will have no effect. future.cancel(true) will interrupt the thread that is executing that task. Whether this will have any effect is up to you, who will implement that task. A task may or may not respond to interruption depending on the implementation.

In order to make your task responsive to cancellation, you must implement doSomething() so that it will respond to interruption.

There are basically two way to do this:

1.Check interruption flag in your logic

public void doSomething(){
    stuff();
    if(Thread.isInterrupted()){ //Don't use Thread.interrupt()!
        return; //Stop doing what you are doing and terminate.
    }
    doLongRunningStuff();
}  

You must occasionally check for the interruption flag, and if interrupted, stop what you are doing and return. Be sure to use Thread.isInterrupted() and not Thread.interrupt() for the check.

2.Act upon Interrupted exception

public void doSomething(){
    try{
        stuff();
    }catch(InterruptedException e){
        //Preserve Interrupted Status
        Thread.currentThread.interrupt();
        return; //discontinue process and terminate
    }

    doLongRunningStuff();
}

When you have any method that throws InterruptedException, be sure to stop what you doing and terminate when one is thrown.

Once you implement your methods in this way, you can call future.cancel(true) to cancel the execution of a running task.

Enno Shioji