Just undo the future returned by scheduledAtFixedRate() :
public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); Runnable r = new Runnable() { @Override public void run() { System.out.println("Hello"); } }; ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS); Thread.sleep(5000L); scheduledFuture.cancel(false); }
Another thing to note is that undoing does not remove the task from the scheduler. All this ensures that the isDone method always returns true. This can lead to a memory leak if you continue to add such tasks. For example, if you start a task based on some client activity or a user interface button, repeat it n times and exit. If this button is pressed too many times, you can get a large pool of threads that cannot be garbage collected because the scheduler still has a link.
You can use setRemoveOnCancelPolicy (true) in the ScheduledThreadPoolExecutor class, available in Java 7 onwards. For backward compatibility, the default value is false.
JB Nizet Jan 20 '13 at 10:26 2013-01-20 10:26
source share